简体   繁体   中英

Angular2 - No provider for service found

I have defined 3 components in my application. AppComponent, MainComponent and TextComponent.

AppComponent contains MainComponent as follows. Note that I have two services I have included in the providers attribute, CommonEventsService, CommonProductEventsService

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

Main component is included in the directives attribute in the AppComponent. The Main component is defined as follows:

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

Note that I have included the TextComponent in the directives attribute above. The TextComponent is defined as follows:

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

The problem is that when the application is loaded, I get the following error.

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

But I have registered the CommonProductEventsService in the AppComponent. So why am I getting this error?

Can't reproduce. See Working Plunker .

Do you have

CommonEventsService
CommonProductEventsService 

in the same file as the components but further below in the file?

Then you either need to move them upwards, use forwardRef or move them into as separate file and import them.

See also
- 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM