我是打字稿的新手,我无法找到优化代码行的替代方法,如下所示。我需要过滤从传递给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);
}
显然它不起作用......有什么建议吗?感谢。
答案 0 :(得分:1)
您仍然必须将回复传递给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);
}