Issue
I am learning AngularJs 17 and created a login application. However, the response of the server is not getting mapped to the object of the Model Class.
Response:
{
"id": 1,
"userName": "admin",
"email": "admin@gmail.com",
"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;
})
);
}
In the service, I am able to hack it using stringify
and then parsing
the same to get the userData in json structure and then I might be able to init a new userObj with that structure but it seems like a dirty way.
In Udemy course, the instructure using angular 11 was able to get the data automatically into ModelClass and in mine (angular 17) its not happening.
Solution
I think the case is wrong, in your API its username
in your interface its UserName
, could you fix that, maybe it will work!
I do not think you need the third argument for post
first the url and then the post body, will be enough!
Angular will automatically convert the API response to an object, there is no need for JSON.parse(JSON.stringify((user))
interface <- please change this if the request also has userName
instead of UserName
else its not needed
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).pipe(
map(user =>{
if(user) {
const userData = user; // <- changed here
this.currentUser = user.userName; // <- changed here
console.log("userData-UserName: ", userData.userName);
console.log("User: ", JSON.stringify(user));
sessionStorage.setItem('currentUser', JSON.stringify(user));
}
return user;
})
);
Answered By - Naren Murali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.