![](/img/trans.png)
[英]Angular2 - Invalid provider error when injecting service into service
[英]Angular2 “No provider for Service!” error when provider is added @NgModule
我有一個應用程序模塊和單個組件應用程序(用於演示我的問題),並收到以下錯誤:
Error in ./AppComponent class AppComponent_Host - inline template:0:0 caused by: No provider for UserService! ; Zone: <root> ; Task: Promise.then ; Value:
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 {
}
我的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;
}
}
我的用戶服務代碼:
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”
導入路徑錯誤:您在下面的/common
和/common
右側使用/Common
。
對於路徑的區分大小寫,Visual Studio和WebStorm不會顯示IntelliSense錯誤。
此外,如果使用Angular 5的AoT模板編譯,您可以獲得“此組件不是模塊的一部分”錯誤,即使它是,因為導入路徑不正確。 如果沒有AoT,這將有效,因此轉換為AoT時會有驚喜。
從app.module.ts
刪除您的服務: UserService
,然后添加component
:
@Component({
selector: 'App',
template: `<h3>App component</h3>
user name: {{userName}}
`,
providers: [UserService]
})
希望這會幫助你。
出現此錯誤的另一個原因 - 我將服務復制到另一個目錄並單獨更新每個文件。 即使第一個文件仍然存在,我得到此錯誤,直到我更新app.module.ts。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.