Recently, I've started exploring TypeScript and I'm facing a challenge in optimizing a specific line of code. The scenario involves filtering an array received from a callback function that is passed to a 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 would like to avoid using 'this'...
return this.http.get(this.itemsUrl).toPromise()
// ...just at this point
.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 || {};
}
The current implementation works fine, but I am interested in adopting a more concise syntax, perhaps leveraging more TypeScript features, as shown below:
getItem(id: number | string): Promise<MyItem> {
return this.http.get(this.itemsUrl).toPromise()
// ...once again here
.then(this.extractData => result.filter(h => h.id === +id)[0])
.catch(this.handleError);
}
Tried the above approach, but it didn't work out as expected. Any suggestions on how I can achieve this? Thank you.