Hi I have an Angular 8 app that posts data to API (REST in PHP). I am able to post the data to the server and create a new record using the code below.
Question: I would like to read the response from the API method. For example I have logic in the API that checks if the record is already created or not. If the account exists then the API Returns
["MSG":"DUPLICATE_FOUND","STATUS":200]
Otherwise it returns
["MSG":"SUCCESS","STATUS":200]
I would like to read property MSG after the subscribe and then apply the logic (ie show the error message, or other action). But when I do console.log(data) it is returned null.
signup component:
this.userService.addNewUser(user).subscribe(
(data) => {
console.log(data);
},
error => console.log(error)
user.service.ts
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
addNewUser (user): Observable<any> {
return this.http.post<any>(endpoint + 'createNewUser', user, httpOptions).pipe(
catchError(this.handleError<any>())
);
}
Thank you.
The problem is that your response is not in the correct format. What Angular is expecting is a valid JSON response, which in your case you get by replacing the square brackets []
by curly brackets {}
, like this:
Before
["MSG": "DUPLICATE_FOUND", "STATUS": 200]
After
{"MSG": "DUPLICATE_FOUND", "STATUS": 200}
You can use some online software to validate your JSON in case of doubt, I like this one .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.