sourcetip

오류: "정의되지 않은 공급자가 있습니다!일반적으로 이것은 당신이 순환적인 의존 관계를 가지고 있다는 것을 의미합니다."

fileupload 2023. 9. 15. 21:16
반응형

오류: "정의되지 않은 공급자가 있습니다!일반적으로 이것은 당신이 순환적인 의존 관계를 가지고 있다는 것을 의미합니다."

여기 제 Angular / TypeScript 응용 프로그램에서 발생하는 다소 쓸모없는 오류가 있습니다.누군가가 오류 메시지를 개선하기 전까지, 우리는 이것을 어떻게 해야 할까요?이런 일이 일어날 가능성이 가장 높은 상황은 무엇입니까?

Uncaught Error: Encountered undefined provider! Usually this means you have a circular dependencies (might be caused by using 'barrel' index.ts files.
    at Object.syntaxError 
    at eval     at Array.forEach (native) [<root>]
    at CompileMetadataResolver._getProvidersMetadata 
    at CompileMetadataResolver.getNgModuleMetadata 
    at CompileMetadataResolver.getNgModuleSummary 
    at eval 
...

오류 메시지를 통해 어떤 공급자가 이 문제를 발생시키는지 알 수 없습니다.이것을 디버그하는 방법은 다음과 같습니다.

  • node_modules@angular\compiler\bundles\compiler.umd.js 파일로 들어갔습니다.
  • "정의되지 않은 프로바이더와 마주쳤습니다!"라는 대사를 찾았습니다.일반적으로 이것은 당신이 원형 의존성을 가지고 있다는 것을 의미합니다.이는 'barrel' index.ts 파일을 사용하기 때문에 발생할 수 있습니다."
  • 추가하기 전에 한 줄console.log('type', type);어떤 파일이 정의되지 않은 공급자인지 확인하려면(다른 관련 변수를 콘솔로 기록할 수도 있습니다).
  • 관련 파일에서 문제의 원인이 된 '배럴' 가져오기를 찾아 정확한 파일 경로 가져오기로 대체했습니다.

저는 이제 다시 시작하겠습니다.ng serve

한 가지 가능성은 서비스와 모듈을 동일한 파일로 선언하는 것과 서비스 전에 모듈을 선언하는 것입니다.

import {Injectable, NgModule} from '@angular/core';

@NgModule({providers: [FooService]}) // WRONG: used before declared
export class FooModule {
}

@Injectable()
export class FooService {
}

먼저 서비스를 선언하여 이 문제를 해결하거나 다음과 같이 사용할 수 있습니다.

import {forwardRef, Injectable, NgModule} from '@angular/core';

@NgModule({providers: [forwardRef(() => FooService)]})
export class FooModule {
}

@Injectable()
export class FooService {
}

는 아직 https://stackoverflow.com/a/51304428/2549593 에 대해 언급할 평판이 없습니다. 하지만 다음 사항을 추가하는 것이 좋습니다.

console.error('\ntype: ', type, '\nproviders: ', (providers || []).map(p => p && (p.name || p.useClass || p.useValue || p.useFactory || p.useExisting)));

공급자 목록과 문제가 있는 모듈이 표시되므로 해당 공급자 목록을 열고 이 공급자 목록을 확인합니다. 정의되지 않음으로 표시된 공급자 목록은 수정해야 합니다.

ng-packagr을 사용하여 라이브러리를 패키지화한 후 다른 라이브러리로 가져오는 과정에서 이 문제가 발생했습니다.결국 제 문제가 된 것은 정말로 '배럴' 지수.ts 수입이었습니다.

이게 깨지게 만드는 거였어요.

import { Activate, Another, Data } from './services
@NgModule({ providers: [ Activate, Another, Data ]})

services 폴더에서 모든 서비스를 내보내는 index.ts 파일을 하나 가지고 있었습니다.

이것이 해결했습니다.

import { Activate } from './services/activate.service.ts'
import { Another} from './services/another.service.ts'
import { Data } from './services/data.service.ts'
@NgModule({ providers: [ Activate, Another, Data ]})

이 오류가 --prod를 실행했습니다.

다음과 같은 것은 가져올 수 없습니다.

import { MyService } from '.';

전체 경로를 사용해야 합니다.

import { MyService } from './my.service'

angular app에서 사용되는 타사 api의 일부 의존성 때문에 이 문제가 발생했습니다.동일한 문제에 직면하여 다음 단계를 통해 해결했습니다.

  1. package.lock.json 파일을 제거했습니다.
  2. 삭제된 node_modules 폴더
  3. npm 설치를 다시 실행합니다.
  4. ng build --prod를 실행하면 문제가 해결됩니다.

모듈이 당신이 언급한 서비스를 찾을 수 있는지 확인합니다.

제 경우에는 수출을 하고 있었습니다.guard나의guards폴더.이 폴더에 index.ts 파일이 들어 있습니다.여기에 두 개의 파일이 더 있었습니다.guards폴더auth.guard.ts그리고.company.guard.ts. 이상적으로 다음과 같이 인덱스로 파일을 내보냈어야 했습니다.

경비/인덱스의 내용

export * from './auth.guard';
export * from './company.guard'; // forgot this 

그런데 위에 수출하는 라인을 포함하는 것을 깜빡했습니다.company.guard.ts. 이것이 문제를 일으키고 있었습니다.

또한 node_modules\@angular\compiler\bundles\compiler.umd.js 파일에 오류 메시지 문 직전에 값을 콘솔에 기록했습니다.

그리고 Document 인터페이스가 구성요소의 Provider 배열에 있는 이 근본 원인인지 확인했습니다.

이 문제를 해결하기 위해 제거했습니다.

내 경우에는 이것을 바꿉니다.

  @Injectable()
    export class LocationTracker {
    }

로.

  @Injectable()
    export class LocationTrackerProvider {
    }

제 경우 서비스에서 @Injectionable() 데코레이터를 삭제했습니다(서비스를 주입할 필요가 없었기 때문입니다).

Ionic의 경우

@NgModule({
providers: [ storage, ... ]
})

@ionic/storage 2.x.x 이후 app.module.ts에서 스토리지 대신 IonicStorageModule을 가져옵니다.

angular class 재정의 가져오기를 놓쳤을 때 이 오류가 발생했습니다.잘못된 수입으로 인해 다른 부분에서도 오류가 발생할 수 있다고 생각합니다.

제 경우에는 수입 명세서가 없었습니다.File그리고 제가 원하는 파일 인터페이스로 기본 설정이 되었습니다.추가하기import { File } from "@ionic-native/file"문제를 고쳤습니다.

@Component({
  selector: "app-dispatching-history",
  templateUrl: "./dispatching-history.component.html",
  styleUrls: ["./dispatching-history.component.css"],
  providers: [RecommendationService, Location, { provide: HashLocationStrategy, useClass: HashLocationStrategy }]
})

그냥 덧붙였어요.Location, { provide: HashLocationStrategy, useClass: HashLocationStrategy }제 컴포넌트 중 하나의 프로바이더로서 app.jp.ts와 같은 파일에 다른 필요한 변경을 하지 않았습니다.저는 더 이상 필요가 없어서 그냥 제거합니다.그리고 명령은ng build -c deploy --build-optimizer --aot --prod --sourceMap다시 작동합니다.

저는 배럴 수입을 모두 평탄화함으로써 이 문제를 해결했습니다(애초 배럴 파일을 사용하려는 목적을 다소 무시하지만, 이 문제에 대해 더 이상 시간을 낭비할 수 없습니다).

제 경우에는, 아주 단순하게도, 모듈 정의에서 정말로 정의되지 않은 프로바이더였습니다.
왜냐하면 제가 사용한 lib는 공급자를 동적으로 변경할 수 있는 옵션이 있었고 잘못 설정되어 있어서 로딩이 되었습니다.undefined제공자로서

마이더Angular projectnpm 사용시angular library패키징 상승 오류:

ERROR in : Encountered undefined provider! Usually this means you have a circular dependencies. This might be caused by using 'barrel' index.ts files.

그 이유는 에 대한 별칭 정의public_api.ts

예제:

// it's wrong
export { HeaderService as HeaderService } from "./lib/services/header.service";
// this is correct
export { HeaderService } from "./lib/services/header.service";

언급URL : https://stackoverflow.com/questions/43008395/error-encountered-undefined-provider-usually-this-means-you-have-a-circular-d

반응형