javascriptangulartypescriptangular2-modules

Angular2 "No provider for Service!" error when provider is added @NgModule


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.

Plunker

am using angular2 version: "2.0.0"


Solution

  • The import path is wrong: you use /Common in one and /common right below.

    Visual Studio and WebStorm will not show IntelliSense errors for case-sensitivity of paths.

    Furthermore, if using Angular 5's AoT template compilation, you can get a "This component is not part of a module" error, even though it is, because the import path is incorrect. Without AoT this will work, so you'll get a surprise when converting to AoT.