2016-05-23 44 views
0

我想要做的是創建一個服務,使用模型來顯示警報。警報模型應該是其他地方無需的,但在該服務中,但我無法完成這項工作。我的服務:Angular2:服務與模型 - 「沒有提供模型」

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) 

我新的角度,我不明白這一點。我錯過了什麼?提前致謝!

回答

1

您需要提供AlertModel某處

bootstrap(AppComponent, [AlertModel]) 

或根組分(優選的):

@Component({ 
    selector: 'my-app', 
    providers: [AlertModel], 
    ... 
}) 

確保AlertModel具有@Injectable()裝飾和設置以及其所有的構造參數(如果有的話)

@Inject(AlertModel)是多餘的,如果第e的構造函數參數已經是AlertModel@Inject()只有在類型不同或AlertModel沒有@Injectable()修飾符時纔是必需的。

constructor(@Inject(AlertModel) alertModel: AlertModel) { 
0

,因爲沒有供應商爲AlertModel類從UserComponent組件(即調用服務)看到你有這樣的錯誤。在引導應用程序時,您可以在組件的providers屬性中定義此類。

見的問題更多地瞭解如何噴射分層工作和如何注入東西放到服務:

由於AlertModel類似乎是一個模型類我不認爲你需要注入它。您可以簡單地導入該類並將其實例化:

@Injectable() 
export class AlertService { 
    alertModel: AlertModel = new AlertModel(); 

    public alert(){ 
    this.alertModel.message = 'success'; 
    //... 
    } 
}