Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()...

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.

like image 307
user3683782 Avatar asked May 22 '26 19:05

user3683782


1 Answers

You still have to pass the response to your extractData method:

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);
}
like image 184
rinukkusu Avatar answered May 24 '26 09:05

rinukkusu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!