12

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?

0

2 Answers 2

40

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"));
}
Sign up to request clarification or add additional context in comments.

2 Comments

I have this code for the read operation getAllUsers() { return this.http.get('/api/users') .map(res => res.json()); } how does return the data without subscribing?
@JackSlayer94 - It wouldn't but you probably use the resulting observable in an async pipe in a template (which would call subscribe) or something else eventually calls subscribe on it.
7

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.