[英]Angular2: Service with Model - “no provider for model”
我正在嘗試做的是創建一個使用模型來顯示警報的服務。 除了該服務外,其他地方都沒有必要使用警報模型,但是我無法進行這項工作。 我的服務:
import {Injectable, Inject} from "angular2/core";
import {AlertModel} from "../models/alert.model";
@Injectable()
export class AlertService {
constructor(@Inject(AlertModel) alertModel: AlertModel) {
}
public alert(){
this.alertModel.message = 'success';
//...
}
}
但我不斷收到此錯誤:
Uncaught (in promise): No provider for AlertModel! (UserComponent -> AlertService -> AlertModel)
我是棱角新手,對此我不理解。 我想念什么? 提前致謝!
您需要在某處提供AlertModel
bootstrap(AppComponent, [AlertModel])
或在根組件中(首選):
@Component({
selector: 'my-app',
providers: [AlertModel],
...
})
確保AlertModel
具有@Injectable()
裝飾器,並且還提供了其所有構造函數參數(如果有)
@Inject(AlertModel)
是多余的,如果構造器參數的類型已經是AlertModel
。 @Inject()
僅在類型不同或AlertModel
沒有@Injectable()
裝飾器時才需要。
constructor(@Inject(AlertModel) alertModel: AlertModel) {
您有此錯誤,因為沒有從UserComponent
組件(調用服務)可見的AlertModel
類的提供程序。 引導應用程序時,可以在組件的providers
屬性中定義該類。
請參閱問題以了解有關分層注入器如何工作以及如何將事物注入服務的更多信息:
由於AlertModel
類似乎是模型類,因此我認為您不需要注入它。 您可以簡單地導入類並實例化它:
@Injectable()
export class AlertService {
alertModel: AlertModel = new AlertModel();
public alert(){
this.alertModel.message = 'success';
//...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.