[英]Wait for function to finish in angular4
我有一部分代碼無法正常運行。
challengeService.getChallenge(1,this.navParams.get("val1",val2))
.map(res => res.json())
.catch(err => {
alert('UI error handling');
alert(err);
return Observable.throw(err); // observable needs to be returned or exception raised
})
.subscribe((data) => {
this.challenge = ((data[0]));
});
return this.challenge;
它與我的challengeservice對話,代碼如下:
getChallenge(val1, val2)
{
this.storage.ready().then(() => {
this.storage.get('jwt').then((val) => {
let authHeader = new Headers();
authHeader.append('x-access-token', val);
this.challenges = this.http.get('http://localhost:8080/api/val3/'+val1+'/'+val2+'', {
headers: authHeader
});
});
});
return this.challenges;
}
在我的代碼的第一部分中,我現在遇到一個映射錯誤(無法對未定義的.map進行映射),因為我的Challenge數組顯然為空。 當我將return語句放在存儲括號中時,該程序na繞不返回數組,而是不返回任何內容(無效)。 如何使我的Challengepage等待我的ChallengeService從api獲取數據並正確填充數據?
提前致謝!
考慮更改http調用的順序和組織,以更緊密地遵循常規做法。
如果您不使用新的HttpClient,則服務代碼通常如下所示:
getProducts(): Observable<IProduct[]> {
return this._http.get(this._productUrl)
.map((response: Response) => <IProduct[]> response.json())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}
請注意,這是響應映射發生的地方。 (我知道您在這里還需要其他一些有關存儲檢查的代碼...但這顯示了地圖的使用方式。)
組件代碼如下所示:
ngOnInit(): void {
this._productService.getProducts()
.subscribe(products => this.products = products,
error => this.errorMessage = <any>error);
}
這是處理訂閱的地方。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.