打字稿语法angular2承诺然后回调
typescript syntax angular2 promise then callback
我是打字稿的新手,我找不到优化代码行的替代方法,如下所示。我需要过滤从我传递给 promise.then()...
的回调函数派生的数组
getAllItems(): Promise<MyItem[]> {
return this.http.get(this.itemsUrl).toPromise()
.then(this.extractData)
.catch(this.handleError);
}
getItem(id: number | string): Promise<MyItem> {
var that = this; // i want to avoid to use this...
return this.http.get(this.itemsUrl).toPromise()
// ...just here
.then(function(res) {
return that.extractData(res).filter(h => h.id === +id)[0];
})
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
上面的代码运行良好,但我想使用更短的(我猜是更多的打字稿)语法来实现类似的东西:
getItem(id: number | string): Promise<MyItem> {
return this.http.get(this.itemsUrl).toPromise()
// ... here again
.then(this.extractData => result.filter(h => h.id === +id)[0])
.catch(this.handleError);
}
显然它不起作用...有什么建议吗?谢谢
您仍然需要将响应传递给您的 extractData
方法:
getItem(id: number | string): Promise<MyItem> {
return this.http.get(this.itemsUrl).toPromise()
// ... here again
.then(res => this.extractData(res).filter(h => h.id === +id)[0])
.catch(this.handleError);
}
我是打字稿的新手,我找不到优化代码行的替代方法,如下所示。我需要过滤从我传递给 promise.then()...
的回调函数派生的数组getAllItems(): Promise<MyItem[]> {
return this.http.get(this.itemsUrl).toPromise()
.then(this.extractData)
.catch(this.handleError);
}
getItem(id: number | string): Promise<MyItem> {
var that = this; // i want to avoid to use this...
return this.http.get(this.itemsUrl).toPromise()
// ...just here
.then(function(res) {
return that.extractData(res).filter(h => h.id === +id)[0];
})
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
上面的代码运行良好,但我想使用更短的(我猜是更多的打字稿)语法来实现类似的东西:
getItem(id: number | string): Promise<MyItem> {
return this.http.get(this.itemsUrl).toPromise()
// ... here again
.then(this.extractData => result.filter(h => h.id === +id)[0])
.catch(this.handleError);
}
显然它不起作用...有什么建议吗?谢谢
您仍然需要将响应传递给您的 extractData
方法:
getItem(id: number | string): Promise<MyItem> {
return this.http.get(this.itemsUrl).toPromise()
// ... here again
.then(res => this.extractData(res).filter(h => h.id === +id)[0])
.catch(this.handleError);
}