從我的組件我打電話給服務中的方法,讓我從API的訂單。從API加載數據的問題 - 想要使用異步/等待代替
我的服務:
getOrder(orderId: number): Observable<Order> {
const url = `${this.ordersUrl}/getOrder?orderId=${orderId}&country=${Cookie.get('country')}`;
return this.http.get(url, {headers: this.headers}).map(response => response.json()).catch(this.errorService.handleError);
}
我的組件:
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.orderId = +params['orderId'];
this.orderService.getOrder(this.orderId)
.subscribe(order => {
this.order = order;
console.log(this.order.commentAdmin);},
error => this.errorMessage = <any>error);
});
當我打開我的模板,我的組件與我從 「命令」 獲得的數據,我得到了數據未定義。但是,如果我console.log它,我得到正確的答案。 我在考慮在加載模板之前加載數據,並且出現了一些錯誤。我想嘗試使用異步並等待獲取並顯示數據,但我不知道如何執行此操作。我們通過使用延遲解決了這個問題,因爲我們之前都沒有使用過Angular。我如何正確使用await和async來做到這一點?
謝謝,這確實刪除了控制檯中的所有警告。那麼通過這樣做,它會等待綁定數據,直到數據從端點返回爲止? – schivv
elvis操作符是三元空值檢查的語法糖。這與'{{order? order.commentAdmin:''}}'。你可以將它們鏈接在一起'訂購?.commentAdmin?.userID',或者甚至可以將它們與'async'管道'(order | async)一起使用?commentAdmin' – theOriginalJosh
我會將此標記爲接受的答案,謝謝。 – schivv