我有一個應用程序模塊和單組分應用(做證明我的問題),並獲得以下錯誤:Angular2「沒有服務提供者!」錯誤時添加提供商@NgModule
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 {
}
代碼:對的AppModule
Error in ./AppComponent class AppComponent_Host - inline template:0:0 caused by: No provider for UserService! ; Zone: <root> ; Task: Promise.then ; Value:
代碼我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;
}
}
我UserService代碼:
import { Injectable, EventEmitter } from '@angular/core';
@Injectable()
export class UserService {
obs$: EventEmitter<any> = new EventEmitter<any>()
userName = 'Sherlock Holmes';
}
現在,如果我添加UserService爲供應商AppComponent,它會解決這個問題。但我不想,因爲我只想在整個應用程序中使用我的服務的一個實例。即使在subModules(功能模塊)中。
根據我的理解,如果我添加服務作爲模塊級供應商,那麼我可以只是將其注入到任何組件下模塊。
這是我正在看的例子。
現在用angular2版本: 「2.0.0」
請發佈您的'UserService';它是用'@Injectable()'裝飾的嗎? (除非當然是Plunker的例子......) – msanford
另外,你的導入路徑可能是錯誤的:你在下面的一個和'/ common'中使用'/ Common' ... – msanford
@msanford post updated,User服務添加。路徑很好,因爲導入的類出現在visual studio intellisense中。 –