Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

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.

share|improve this question
up vote 1 down vote accepted

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);
}
share|improve this answer
    
thanks man, very helpful. – user3683782 Jun 29 at 15:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.