Angular 4.0 http put request

后端 未结 3 932
天命终不由人
天命终不由人 2021-01-07 14:13

I\'ve written a function to send a http put request to update some data but it says, that it is not recieving any data:

updateHuman(human: Human) {
    const         


        
相关标签:
3条回答
  • 2021-01-07 14:39

    In the second example you are not returning the response within the map, you are returning the human that was originally passed in.

    So, basically you are creating an illusion that it is working, when it isn't.

    Probably best to test your API with something like PostMan, to see if you can get it working with that first.

    0 讨论(0)
  • 2021-01-07 14:50

    You use map method incorrectly, read more about this method in documentation: http://xgrommx.github.io/rx-book/content/observable/observable_instance_methods/map.html

    If you want receive response from server your code should look like that:

    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)
        );
    }
    

    You can use map method if you want to modify server response(map some objects to other 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() }) // you can get json response here 
        .subscribe(
            response => response.data as Human, // -- change here --
            error => console.log(error)
        );
    }
    

    map method returns Observable object, so you can subscribe that and wait for response, error or simple complete method(third parameter of subscribe()): http://xgrommx.github.io/rx-book/content/observable/observable_instance_methods/subscribe.html

    0 讨论(0)
  • 2021-01-07 15:00

    Observables are lazy, you need to be subscribed to them for them to work and retrieve anything. Did you subscribe to your method? Example:

    methodToUpdateHuman(human): void{
    ...
    this.updateHuman(human).subscribe((response) => {
       //do something with the response
       console.log.("Response is: ", response);
    },
    (error) => {
       //catch the error
       console.error("An error occurred, ", error);
    });
    }
    

    I suggest you read through the Angular Tour Of Heroses, it's based in angular 2 and most of the functionality is functional in angular 4, there is a section dedicated to http requests: https://angular.io/tutorial/toh-pt6

    0 讨论(0)
提交回复
热议问题