Within my Angular application, I make calls to multiple APIs depending on the user's role - whether they are a regular user, super user, or admin.
For each type of user, there is a designated dashboard that they should be directed to after login.
.service.ts:
public errors: any = [];
public userProfile: any;
userType: any;
dataLog = {
location : "lat: "+localStorage.getItem('lt')+",lng:"+localStorage.getItem('lt'),
action : "Dashboard View",
login_status: 1
}
//Upon logging in, I need to fetch user profile using the following API call:
public login(user) {
this.http.post(environment.apiUrl+'/api/login', JSON.stringify(user), this.httpOptions).subscribe(
data => {
this.updateData(data['token']);
localStorage.setItem('token',data['token']);
var jsons=this.dashboardService.create('',this.token);
this.userProfile();
let userProfile = JSON.parse(localStorage.getItem('profile'));
let httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Token ' + this.token
})
};
if(userProfile.usertype === 'Admin'){
this.http.post(environment.apiUrl+'/api/activity/adminsession',JSON.stringify(this.dataLog), httpOptions).subscribe(
(dataforlogin1)=>{
console.log(dataforlogin1);
},
err=>{
console.log("Error",err)
}
);
}
else if(userProfile.usertype === 'Super User'){
this.http.post(environment.apiUrl+'/api/activity/superusersession',JSON.stringify(this.dataLog), httpOptions).subscribe(
(dataforlogin2)=>{
console.log(dataforlogin2);
},
err=>{
console.log("Error",err)
}
);
}
else{
this.http.post(environment.apiUrl+'/api/activity/usersession',JSON.stringify(this.dataLog), httpOptions).subscribe(
(dataforlogin3)=>{
console.log(dataforlogin3);
},
err=>{
console.log("Error",err)
}
);
}
},
userProfile() {
let httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Token ' + localStorage.getItem('token')
})
};
this.http.get(environment.apiUrl+'/profile', httpOptions).subscribe(
(profile:any)=>{
localStorage.setItem("profile",JSON.stringify(profile));
console.log("profile:",JSON.parse(localStorage.getItem("profile")))
if(profile.usertype==="Admin"){
this.router.navigate(['/admin']);
}
else if(profile.usertype==="Super User"){
this.router.navigate(['/superuser']);
}
else{
this.router.navigate(['/dashboard']);
}
},
err=>{
console.log("Error",err)
}
);
}
The functionality works as expected. However, upon removing the localStorage information through developer tools, the dashboard data does not display and an error message appears:
Cannot read property 'usertype' of null
at SafeSubscriber.http.post.subscribe.errors
I would appreciate any assistance in resolving this issue.