javascript - 如何在建構子中使用非同步呼叫注入服務,Angular 2
問題是:我有一個服務在建構函式中發出 HTTP 請求:
constructor(public http: Http, public geolocation: Geolocation) {
this.http = http;
this.geolocation = geolocation;
//Http request... this will set variable forecast of the class when complete.
this.getForecast(16);
}然後我像這樣在組件中注入那個服務:
constructor(public connector: ApiConnector) {
this.forecast = connector.forecast;
}如果我像這裡這樣嘗試在元件裝飾器上使用元件類別的 forecast 成員:
@Component({
selector: 'app',
directives: [MainForecast, DailyForecast],
template: `
<main-forecast [main-weather]="forecast"></main-forecast>
<daily-forecast [weather-list]="forecast.list"></daily-forecast>
`,
})我收到一個錯誤,『無法讀取未定義的屬性 'list' 在...』
在組件的建構函數中有可能使用 Promise 嗎?
答案#1
Angular2 建議在 ngOnInit 內進行繁重的工作,而不是在建構函式內。
ngOnInit 是一個生命週期掛勾/事件。
答案#2
你正在試圖繞過 Angular 的生命週期。
看起來你假設你的服務是在啟動時啟動的。事實並非如此。即使你的服務是在根級別提供,它也可能只是即時初始化的。你可能需要在啟動邏輯期間調用一些公共初始化方法以確保它被初始化。