I have an app module and single component application (made to demonstrate my problem), and getting following error:
Error in ./AppComponent class AppComponent_Host - inline template:0:0 caused by: No provider for UserService! ; Zone: <root> ; Task: Promise.then ; Value: code for AppModule:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { UserService } from './components/common/userservice'; @NgModule({ imports: [ BrowserModule, ], declarations: [ AppComponent ], providers: [UserService], bootstrap: [AppComponent], entryComponents: [] }) export class AppModule { } Code for my AppComponent:
import { Component} from '@angular/core'; import { UserService} from './userservice'; @Component({ selector: 'App', template: `<h3>App component</h3> user name: {{userName}} `, providers: [] }) export class AppComponent { userName: string; constructor(userService: UserService) { this.userName = userService.userName; } } My UserService Code:
import { Injectable, EventEmitter } from '@angular/core'; @Injectable() export class UserService { obs$: EventEmitter<any> = new EventEmitter<any>() userName = 'Sherlock Holmes'; } Now if i add UserService as provider to AppComponent, it will solve the issue. but i dont want to, because i want only one instance of my service in whole application. Even in subModules(feature modules).
according to my understanding, if i add service as provider on module level, then i can just inject it to any component under module.
here is am example i was watching.
am using angular2 version: "2.0.0"
UserService; is it decorated with@Injectable()? (Unless it's exactly what's in the example Plunker of course...)/Commonin one and/commonright below...