在Angular 2中将标记值注入全局容器,无法解析所有参数

时间:2017-05-17 16:17:19

标签: angular dependency-injection

我正在尝试根据official documentation在Angular 2中为我的应用程序的DI容器注入全局值。

然而,我收到一个错误:

compiler.es5.js:1540 Uncaught Error: Can't resolve all parameters for AppComponent: (?).
    at syntaxError (http://localhost:4200/vendor.bundle.js:30216:34)
    at CompileMetadataResolver._getDependenciesMetadata (http://localhost:4200/vendor.bundle.js:43553:35)
    at CompileMetadataResolver._getTypeMetadata (http://localhost:4200/vendor.bundle.js:43421:26)
    at CompileMetadataResolver.getNonNormalizedDirectiveMetadata (http://localhost:4200/vendor.bundle.js:43030:24)
    at CompileMetadataResolver._getEntryComponentMetadata (http://localhost:4200/vendor.bundle.js:43674:45)
    at http://localhost:4200/vendor.bundle.js:43257:110
    at Array.map (native)
    at CompileMetadataResolver.getNgModuleMetadata (http://localhost:4200/vendor.bundle.js:43257:73)
    at JitCompiler._loadModules (http://localhost:4200/vendor.bundle.js:54306:66)
    at JitCompiler._compileModuleAndComponents (http://localhost:4200/vendor.bundle.js:54265:52)

这是我的课程:

app.module.ts

import {BrowserModule} from '@angular/platform-browser';
import {InjectionToken, NgModule} from '@angular/core';

import {AppComponent} from './app.component';

export interface AppConfig {
  apiEndpoint: string;
  title: string;
}

export const HERO_DI_CONFIG: AppConfig = {
  apiEndpoint: 'api.heroes.com',
  title: 'Dependency Injection'
};

export let APP_CONFIG = new InjectionToken<AppConfig>('app.config');


@NgModule({
  imports: [
    BrowserModule
  ],
  declarations: [
    AppComponent
  ],
  providers: [
    { provide: APP_CONFIG, useValue: HERO_DI_CONFIG }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

app.component.ts

import {Component as NgComponent, Inject} from '@angular/core';
import {APP_CONFIG, AppConfig} from './app.module';


@NgComponent({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent {
  constructor (@Inject(APP_CONFIG) config: AppConfig) {
    console.log(config.apiEndpoint, config.title);
  }
}

可能是什么问题以及我应该使用什么调试策略?错误和堆栈跟踪在这里并没有真正帮助我。

1 个答案:

答案 0 :(得分:3)

正如@yurzui所述:@Inject() for InjectionToken declared in module fails in angular2

您应该将export let APP_CONFIG = new InjectionToken<AppConfig>('app.config');移到单独的文件中,因为它会导致循环依赖性问题。