This is the code from my last question:
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');
}
});
}
But when I am trying to access userRole after calling this function, I get userRole undefined, maybe due to it gets returned before .subscribe gets hit.
As a result I get this as undefined:
var result = this.getUserRole(token);
console.log('Call from login ' + result);
So, I have changed the approach to be something like this:
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;
}
But here I am getting result as [object object].
May I know which approach should I go with to immediately get userRole assigned by either method.
In second method I am not able to convert [object object] into the value.
The data I receive from API is something like this:
["school"]
This is the calling:
this.getUserRole(token);
console.log('Call from login ' + this.userRole);
This is inside getUserRole function:
var result = this.http.get(`${this.baseURL + this.loginApiRoot}/GetUserRoles`, options).subscribe(data => {
this.userRole = JSON.stringify(data);
console.log(data);
});
And this is the sequence of console I am getting:
Call from login undefined
Response {_body: "["school"]", status: 200, ok: true, statusText: "OK", headers: Headers, …}
So, even trying the code with subscribe, the assignment of userRole is getting latter by calling from login.
HttporHttpClient?