Exploring the world of HTTP PUT requests in Angular 4.0

I have encountered an issue with a function I wrote for sending an http put request to update data. The function is not receiving any data:

updateHuman(human: Human) {
    const url = `${this.url}/${human.id}`;
    const data = JSON.stringify(human);
    return this.http.put(url, data).map(
        response => response.json().data as Human,
        error => console.log(error)
    );
}

However, when I made some changes to the function as shown below, it started working without any issues:

updateHuman(human: Human) {
    const url = `${this.url}/${human.id}`;
    const data = JSON.stringify(human);
    return this.http.put(url, data).map(() => human);
}

I am curious to know why the first version of the function did not work while the second one works perfectly. Can anyone provide an explanation?

Answer №1

Observables are like that friend who waits for you to ask before offering help. You must subscribe to them in order to see any results. Have you subscribed to your method yet? Here's an example:

updateHumanDetails(human): void {
...
this.updateHumanInfo(human).subscribe((response) => {
   //do something with the response
   console.log("Response received: ", response);
},
(error) => {
   //handle errors
   console.error("An error occurred: ", error);
});
}

I recommend checking out the Angular Tour Of Heroes, it's focused on angular 2 but still relevant for angular 4, especially the section on making http requests: https://angular.io/tutorial/toh-pt6

Answer №2

The scenario presented in the next example involves not properly returning the response within the map function, but instead returning the original human object that was initially provided.

Essentially, this creates a false impression that the code is functioning correctly when, in reality, it is not.

It would be advisable to conduct API testing using tools like PostMan to confirm whether it can be successfully implemented in that context.

Answer №3

You are utilizing the map method incorrectly; it would be beneficial to familiarize yourself with its proper usage by referencing the documentation:

If you intend to receive a response from the server, your code should resemble the following:

updateHuman(human: Human) {
    const url = `${this.url}/${human.id}`;
    const data = JSON.stringify(human);
    return this.http.put(url, data).subscribe(
        response => response.json().data as Human,
        error => console.log(error)
    );
}

The map method can be utilized to modify server responses (mapping objects to different structures, etc.):

updateHuman(human: Human) {
    const url = `${this.url}/${human.id}`;
    const data = JSON.stringify(human);
    return this.http.put(url, data)
    .map(response => { return response.json() }) // accessing json response here 
    .subscribe(
        response => response.data as Human, // -- amend here --
        error => console.log(error)
    );
}

The map method returns an Observable object, allowing you to subscribe and await responses, errors, or completion using the complete method (third parameter of subscribe()):

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 the significance of using @Injectable for our services in Angular2?

Greetings, fellow developers: As a novice in the realm of Angular2, I found myself facing some confusion when delving into the dependency injection section. Specifically, the @Injectable() notation left me scratching my head a bit. In order to clarify my ...

What is the best way to save information from an axios promise into my database on separate lines?

Having a technical issue and seeking assistance: Currently, I am encountering an issue with my axios request to the database. After successfully retrieving the data, I aim to display it in a select form. However, the response is coming back as one continu ...

Uh-oh! An unexpected type error occurred. It seems that the property 'paginator' cannot be set

I am developing a responsive table using Angular Material. To guide me, I found this helpful example here. Here is the progress I have made so far: HTML <mat-form-field> <input matInput (keyup)="applyFilter($event.target.value)" placeholder ...

The animation of the splash screen in Angular is quite jarring and lacks fluidity

I am experiencing some issues with my angular splash screen animation. It works perfectly when there is no activity in the background, but when I simulate a real-life application scenario, the animation becomes stuttered, choppy, or sometimes does not anim ...

Using Ruby variable as a parameter in JavaScript

Is there a way to include a ruby variable as a parameter in a JavaScript function for a Rails checkbox? Here is an example of what I'm trying to do: <%= check_box_tag 'Sugestão', prato.id , prato.sugestao,:class => prato.categoria_pr ...

Generate HTML table with CSS dynamically applied through jQuery

After performing some calculations and applying CSS rules using the .css() function in jQuery to color the background of a table, I am facing an issue when trying to print the page. The printed page appears in black and white without retaining any styling ...

Utilizing an EJS template within an express.js application to extract and assign data to a variable

Is there a way to transfer data from my node.js (express) app directly to a variable within the <script> tag on the page? On the server-side, I have the following code: let tmp = JSON.stringify(await f(i)); console.log(tmp); //correct data [{"i ...

What is the origin of the second parameter in an arrow function that returns another arrow function in a React component with Redux?

I'm having trouble understanding where the (val) parameter is coming from in the returned arrow function. I understand that max/minLength is an arrow function taking an argument set on the input field (3 and 25), and it returns another arrow function ...

What is the best way to transfer information between two separate Javascript controller files?

My current situation is a bit complex, but I believe there must be a straightforward solution. I have two Javascript controller files: one named rootPageClient.js and another called findPollClient.js. Additionally, there's a file called ajax-function ...

403 Forbidden error encountered while making a REST API call using jQuery AJAX

Attempting to create a basic jQuery ajax call to an API Here is the code I'm using: jQuery.ajax({ type: "GET", url: "http://example.com/api/v1/testapi", headers: { "Authorization": "Basic Ylc5aWXXXXXXlk1ucWx5ZnA=" }, success: fu ...

I am having trouble getting the filter functionality to work in my specific situation with AngularJS

I inserted this code snippet within my <li> tag (line 5) but it displayed as blank. | filter: {tabs.tabId: currentTab} To view a demo of my app, visit http://jsfiddle.net/8Ub6n/8/ This is the HTML code: <ul ng-repeat="friend in user"> ...

Tips for avoiding the default rendering of Nuxt 3 layout?

After reviewing the Nuxt 3 documentation and finding it lacking in explanation, I turned to the Nuxt 2 docs. According to them, the default layout should be replaced by a specific layout specified within the name property of the <nuxt-layout> compone ...

How to activate select only when specific options are chosen using jQuery

I am working on a form that has 1 select element disabled, with 4 options. I am looking to implement a jQuery function that will perform the following actions: If OPTION #1 is clicked, it should check if any other options are selected and reset them (eras ...

Is it acceptable to assign a value to exports.new?

In my venture with Node.js and Express, I am aiming for simplicity. Drawing from my experience with Rails, I am following the RESTful structure typical in Rails applications. In setting up my controllers (or routes), I want them to resemble this: // route ...

Is jest the ideal tool for testing an Angular Library?

I am currently testing an Angular 9 library using Jest. I have added the necessary dependencies for Jest and Typescript in my local library's package.json as shown below: "devDependencies": { "@types/jest": "^25.1.3", "jest": "^25.1.0", ...

Combining Google app endpoints with a phonegap app: Step-by-step guide

I've been working on a Phonegap client application and have developed all the necessary web services using Google Endpoints. However, I am facing an issue with using the API. In my index.html file, there is this script: <head><script> ...

Trouble with references in Vue TypeScript when trying to access child component methods

I'm encountering an issue with calling a function in a child component while using typescript <notification ref="notification"></notification> <button @click="$refs.notification.show()"></button> Is there a ...

One package in Node.js, a pair of dependencies, and a single export utilizing ES6 syntax

Currently, the library contains multiple frameworks in one npm module (which is admittedly not the best practice). However, as we work on splitting the library into separate JS framework specific repositories like React, JQuery, Angular, etc., I'm fac ...

The hiding/showing of elements is not being executed correctly by jQuery

My web template includes HTML and jQuery code for a project I'm working on. During the $.getJSON call, there can be a delay in loading the data. To inform the user to wait, I added a warning message in a div with the id="warning". The code properly ...

Issues with routing in NodeJS Express causing routes to not be called

I've been working on setting up a basic REST API using nodeJS. However, I am facing an issue where none of the endpoints are being called when I try to access them. Can someone guide me on what changes I need to make in order to get it working properl ...