Angular 4.0 http put request

后端 未结 3 929
天命终不由人
天命终不由人 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: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

提交回复
热议问题