Angular 4 - HTTP delete not working

2020-07-06 20:27发布

问题:

I am trying to create a MEAN crud operation. I have an api in node with the delete http method as so localhost:3000/api/user?id=<some document id>. Below is the angular code I use:

deleteUser(user) {
    console.log("user to delete:" + user._id);
    let myParams = new URLSearchParams();
    myParams.append('id', user._id);
    return this.http.delete('/api/user', { search: myParams })
      .map(res => res.json());
}

The correct id is being printed to console but I am not able to see even the call being made in the chrome network bar nor has the data being deleted. Any ideas what is going wrong?

回答1:

You have to subscribe to the call if you want it to execute. See the HttpClient documentation.

Note the subscribe() method. All Observables returned from HttpClient are cold, which is to say that they are blueprints for making requests. Nothing will happen until you call subscribe(), and every such call will make a separate request. For example, this code sends a POST request with the same data twice:

Example:

otherMethod(){
    this.userService.deleteUser(user).subscribe(() => console.log("user deleted"));
}


回答2:

If you are calling this method inside your component, use .subscribe()

this.userService.deleteUser(user).subscribe(() => console.log("user deleted")); this.errorMessage = error);


标签: angular