In my previous question, I shared the code below:
getUserRole() {
const headers = new Headers();
headers.append('Authorization', `Bearer ${this.getToken()}`);
console.log(this.getToken());
const options = new RequestOptions({ headers: headers});
return this.http.get(`${this.baseURL + this.loginApiRoot}/GetUserRoles`,options).pipe(map(res => res.json()))
.subscribe(data => {
this.userRole = JSON.stringify(data);
if (this.userRole === 'parent') {
this.logout();
} else if (this.userRole === 'school') {
this.isUser = true;
this.isAdmin = false;
this.cookieService.set('isSchool', '1');
} else if (this.userRole === 'admin') {
this.isUser = false;
this.isAdmin = true;
this.cookieService.set('isAdmin', '1');
}
});
}
After calling this function, trying to access userRole
results in undefined
, possibly because it gets returned before .subscribe
is executed.
This leads to undefined
being logged here:
var result = this.getUserRole(token);
console.log('Call from login ' + result);
To address this issue, I modified the approach like so:
getUserRole(roletoken: string) {
const headers = new Headers();
headers.append('Authorization', `Bearer ${roletoken}`);
const options = new RequestOptions({ headers: headers});
var result = this.http.get(`${this.baseURL + this.loginApiRoot}/GetUserRoles`, options).pipe(map(res => res.json()));
console.log(result);
return result;
}
However, this change causes result
to be displayed as [object object]
.
I am seeking guidance on which method should be used to promptly assign the value of userRole
using either approach.
The data received from the API looks like this:
["school"]
This is how the function is called:
this.getUserRole(token);
console.log('Call from login ' + this.userRole);
Within the getUserRole
function:
var result = this.http.get(`${this.baseURL + this.loginApiRoot}/GetUserRoles`, options).subscribe(data => {
this.userRole = JSON.stringify(data);
console.log(data);
});
Here is the order of console outputs achieved:
Call from login undefined
Response {_body: "["school"]", status: 200, ok: true, statusText: "OK", headers: Headers, …}
Even with using subscribe, the assignment of userRole
is happening later when called from login.