[英]typescript syntax angular2 promise then callback
i'm new to typescript and i can't find an alternative to optimize a line of code as you can see below. 我是打字稿的新手,我找不到优化代码行的替代方法,如下所示。 I need to filter an array derived from a callback function that i pass to a promise.then()...
我需要过滤从我传递给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 || { };
}
Code above works well but i want to use a more short(more typescript i guess) syntax to achieve something like: 上面的代码运行良好,但我想使用更短(更多的原型我猜)语法来实现类似的东西:
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);
}
obviously it does not work...any suggestion please? 显然它不起作用...有什么建议吗? Thanks.
谢谢。
You still have to pass the response to your extractData
method: 您仍然必须将响应传递给
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.