When someone registers, I post the info to my back-end. When successfully registering a user, I get a json response back of {success: true, msg: "User registered"}. My problem is when I try to do an if statement to check if success is set to true.
Here is my code that isn't working:
// Register User
this.apiService.registerUser(user).subscribe(data => {
if(data.success) {
this.flashMessage.show('Registration successful', { cssClass: 'alert-success', timeout: 3200 });
} else {
this.flashMessage.show('Registration failed', { cssClass: 'alert-danger', timeout: 3200 });
}
});
I was able to console.log the response of data, and it returned:
{success: true, msg: "User registered"}
Here is the code from my ApiService:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { User } from '../models/User';
@Injectable({
providedIn: 'root'
})
export class ApiService {
private baseUri: string = 'http://localhost:5000/api';
private headers = new HttpHeaders().set('Content-Type', 'application/json');
constructor(private http: HttpClient) { }
registerUser(user: User) {
return this.http.post(this.baseUri + '/register', user, { headers: this.headers });
}
}
Here is the code from my Register Component:
onRegisterSubmit() {
const user: User = {
firstName: this.firstName,
lastName: this.lastName,
email: this.email,
username: this.username,
password: this.password
};
// Register User
this.apiService.registerUser(user).subscribe(data => {
console.log(data);
});
}
Screenshot of error from ng serve
I'm quite new to working with angular let alone a back-end, so if you could explain why this error was occurring it would be greatly appreciated.
Please let me know if you need any more information.
successa result of what's being returned from thePOST, or are you trying to access something on theHttpResponseitself?successis a result of what's being returned from thePOST. Here is a screenshot of the console error i.sstatic.net/9rCBR.pngresasany. So it should be like this:this.http.post('http://localhost:3000/api', obj).subscribe((res:any) => { console.log(res.success) }