I have been studying AngularJS 17 and recently developed a login application. However, I am facing an issue where the server response is not being properly mapped to the object in the Model Class.
Response:
{
"id": 1,
"userName": "admin",
"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2243464f4b4c62454f434b4e0c414d4f">[email protected]</a>",
"password": "",
"role": 1,
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNzA1NzQwMTkzLCJleHAiOjE3MDU3NDE5OTN9.obH83er-eb0Pcl_OLXhwPj7kXUy9lNh0EK3NInr3Eas"
}
Model:
export class LoginViewModel {
UserName: string;
Password: string;
constructor(){
this.UserName = "";
this.Password = "";
}
}
Service:
public Login(loginViewModel: LoginViewModel): Observable<LoginViewModel> {
return this.httpClient.post<LoginViewModel>(this.NODE_HOST + "/api/authenticate",loginViewModel,{responseType: "json"}).pipe(
map(user =>{
if(user) {
var userData = JSON.parse(JSON.stringify(user));
this.currentUser = user.UserName;
console.log("userData-UserName: ", userData.userName);
console.log("User: ", JSON.stringify(user));
sessionStorage.setItem('currentUser', JSON.stringify(user));
}
return user;
})
);
}
Within the service code, I found a workaround by using stringify
and then parsing the data to obtain the user data in JSON format. However, it feels like a messy solution.
In a Udemy course on Angular 11, the instructor was able to automatically receive the data into the ModelClass, but in my case (Angular 17), this automatic mapping is not happening as expected.