簡體   English   中英

Angular2-找不到服務提供者

[英]Angular2 - No provider for service found

我在應用程序中定義了3個組件。 AppComponent,MainComponent和TextComponent。

AppComponent包含MainComponent如下。 請注意,提供者屬性中包含兩個服務,CommonEventsService,CommonProductEventsService

@Component({
  selector: 'my-app',
  template: `
    <my-main></my-main>
  `,
  providers: [CommonEventsService, CommonProductEventsService],
  directives: [ROUTER_DIRECTIVES, MainComponent]
})
export class AppComponent implements OnInit, OnDestroy  {...}

主要組件包含在AppComponent的指令屬性中。 主要組件定義如下:

@Component({
  template: "<my-add-text></my-add-text>",
  selector: "my-main",
  directives: [TextComponent]
})
export class MainComponent implements OnInit, OnDestroy {...}

請注意,我在上面的指令屬性中包含了TextComponent。 TextComponent的定義如下:

@Component({
  selector: "my-add-text",
  templateUrl: "/app/scripts/components/add/text.component.html",
})
export class TextComponent {
 constructor(private commonProductEvents: CommonProductEventsService){}
}

問題是,在加載應用程序時,出現以下錯誤。

EXCEPTION: No provider for CommonProductEventsService! (TextComponent ->   CommonProductEventsService) in [addText in MainComponent@41:13]

但是我已經在AppComponent中注冊了CommonProductEventsService。 那我為什么會收到這個錯誤?

無法復制。 請參閱工作柱塞

你有

CommonEventsService
CommonProductEventsService 

在與組件相同的文件中,但在文件的下面?

然后,您需要向上移動它們,使用forwardRef或將它們移動到單獨的文件中並導入它們。

也可以看看
-https : //angular.io/docs/ts/latest/api/core/forwardRef-function.html-http://blog.thoughtram.io/angular/2015/09/03/forward-references-in-angular -2.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM