Learning how to utilize the angular2 promise `then` callback in TypeScript

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.

Answer №1

Make sure to call your extractData function with the response:

retrieveItem(id: number | string): Promise<MyItem> {
    return this.http.get(this.itemsUrl).toPromise()
        // ... handling here
        .then(res => this.extractData(res).filter(item => item.id === +id)[0])
        .catch(this.handleError);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is preventing me from implementing my JavaScript event on my EJS code?

Looking to add a click event to the image in my EJS file, here's the EJS code snippet: <div class="container" id="comments"> <div class="row"> <div class="col-lg-12"> <div class="well"> ...

How can I create a dynamic search function for an HTML table that contains textboxes within each row as the data, allowing users to search by inputting keywords

Here is the HTML code I have created to fetch data from a database using <sql:...>, iterate through it using <c:forEach ...>, and display the data in textboxes within tr. However, I am facing an issue while trying to implement a dynamic search ...

Leveraging babel-cli on your local machine

Is it possible to utilize the babel client without the need for global installation? Instead of following this method npm install -g babel-cli I am looking to achieve the same outcome by using npm install babel-cli --save-dev ...

What is the best way to proceed with the execution of the statement once the promise has

Within my template, I have utilized the following directory. To change the model value of the drop-down to "id," I implemented the code below: <md-select flex class="md-select-form" ng-model="education.degree" placeholder="Degree" save-id id="educatio ...

Serialize a web form to transmit it through Ajax requests

I am looking to utilize Ajax to send a form instead of using a submit button. In the code below, I have defined the form and added a jQuery function to handle the action when the CREATE BUTTON is clicked. During debugging, I found that console.log($(&ap ...

Babel Compile disrupts the flow of commands

I'm facing an issue while attempting to launch my development server after Babel successfully compiles my files. However, the command chain seems to halt right after Babel displays the compilation success message. Babel has completed compiling 82 f ...

What to do when CSS Overflow doesn't work as expected?

Are there any alternatives for browsers that don't support CSS overflow? I am working on a new layout that heavily relies on the overflow property, however it seems like android browsers do not handle it well and as a result, my layout is broken. I am ...

Angular - the ngFor directive causing function to be executed repeatedly

I need help with a template: <mat-card *ngFor="let cargo of cargos" class="cont-mat"> ... <mat-checkbox *ngFor="let truck of (retrievingTrucksByUserIdAndRules(cargo.id) | async)" formControlName="truckId" ...

Issue with jQuery :contains function in Internet Explorer 7 (jQuery version 1.3.5)

I am attempting to locate a specific text within a div. My code functions properly in all web browsers except for IE7. Here is the snippet of code I am using: <div class="example"> Preview </div> Jquery Code: $(".example:contains(' ...

Updating the input value of one field by typing into another field is not functioning properly when trying to do so for

I'm managing a website with a form that has three fields which can be duplicated on click. Here is an excerpt of my code: $(document).ready(function() { var max_fields = 10; var wrapper = $(".container1"); var add_button = $("#niy"); var ...

Is it possible to dynamically insert additional fields when a button is clicked?

My FormGroup is shown below: this.productGroup = this.fb.group({ name: ['', Validators.compose([Validators.required, Validators.maxLength(80)])], desc: ['', Validators.maxLength(3000)], category: ['', Validators.require ...

Is it possible to identify macOS command keys using JavaScript?

Is there a way to detect macOS command keys using JavaScript? I am looking to specifically identify the left and right command keys. Although I know the key codes for both, I am unsure how to distinguish them from other keys. ...

Updating the background of a button with Vue JS by utilizing an object upon clicking

If you have three buttons and want to change the background color when clicked, for example, clicking on the red button should turn the background color red. However, there is an important detail here: if you click on one button and then another, the old c ...

The AngularJS ngInfiniteScroll feature continues to trigger even as I scroll upwards

When I scroll upwards, it triggers my infiniteSubjects() function. However, I only want it to trigger while scrolling downward. I've searched through various posts but haven't found a solution yet. I've tried using the infinite-scroll-disabl ...

What's the best way to import STL files in Three.js?

Currently, I am developing an application tailored for mechanical design and simulation tasks. Our goal is to incorporate Three.js for loading and visualizing parts created in Solidworks, most commonly exported as STL files in text or binary format. Altho ...

Uploading images with Angular

I have been attempting to utilize ngx-image-cropper for image uploads in my application but am encountering an issue with saving the cropped image. When I try to save the original file loaded through input type="file", everything functions correctly and th ...

The drop-down menu appears to be falling behind the 'content' div element

Whenever I try to hover over the dropdown menu, it frustratingly appears behind the content div that I painstakingly created. Despite all my efforts with z-index adjustments, the issue still persists. Below you'll find all the code for my website, but ...

Order of callback execution in jQuery's ready function

When two JavaScript functions on a page need to be called once the document load is complete, is there a possibility that one function could be executed before the other, or will it always be the same order? For example, using jQuery with the following co ...

Navigating Angular's Resolve Scope Challenges

As a junior developer, I've been diving into Angular.js and exploring the resolve feature of the route provider to preload my Project data from a service before the page loads. Previously, I was fetching the data directly inside the controller. Howeve ...

Tips for toggling the visibility of a website section and updating the image with JavaScript

UPDATE #1 A big thank you to the two helpful users who provided solutions that worked perfectly! In my original post, I forgot to ask if there is a way to adjust the user's view so that when they collapse the expanded section, their "view" on the web ...