I am unsure if I'm fully understanding Observables in Angular as my Observable is not "triggering" or getting any information from subscribe when called. I'm making a simple login system and am trying to get a message from the Http post that it was successful, I have the following Observable function in my user service
addUser(user: User) : Observable<any> {
var headers = new HttpHeaders()
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:4000/api/users/add', user,{headers:headers}).pipe(
map((response: any) => response.json())
);
}
Then I have a register component with a function, onSubmit
, that is called when the form is submitted. This function calls addUser
from the service to send a new user to the API and add them to the database.
onSubmit(): void {
this.userService.addUser(this.user)
.subscribe(res => {
console.log("Registration successful");
this.isSuccessful = true;
},
err => {
console.error("Registration failed: " err);
this.isSignUpFailed = true;
}
);
}
The Http post call works, my API/Backend receives the data and successfully adds a user to the database. My issue is in Angular, the Observable never gives the information or response that it was successful, meaning, it never executes the following in the subscription call in the onSubmit
function
console.log("Registration successful");
this.isSuccessful = true;
I believe this is due to a misunderstanding of Observables on my part but I am unsure of how to fix it even after looking at several other examples.
CodePudding user response:
just Remove the pipe and it will work fine there is no need for response.json
check your console you find something like these error
Registration failed: TypeError: response.json is not a function
addUser(user: User): Observable<any> {
var headers = new HttpHeaders();
headers.append("Content-Type", "application/json");
return this.http
.post("https://jsonplaceholder.typicode.com/posts", user, {
headers: headers
})
}
CodePudding user response:
Turns out it had nothing to do with Angular. Silly mistake, the issue was my API was not sending any information back after it called post, it would add the data to the database but not return any kind of message which would be why the Observable did not react. Simply, I was using an Observable that called a function that manipulated data, the HTTP request, but returned nothing. My assumption was that the HTTP status would automatically return something for the Observable.