I am trying to implement canActivate for user routes, before that I want to check whether the access token is still valid or not. Therefore I implement something like this
export class AuthGuard implements CanActivate {
data:Array<Object>;
constructor(private base: BaseService){}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
var session: any = { token: localStorage.getItem('abc') };
this.base.valid(session).subscribe(result => {
this.data=result;
console.log(this.data); <-- first
});
console.log(this.data); <-- second
return true;
}
}
here I can get the data variable inside the subscribe method when I console it but outside this method is give undefined
value. How can I access it outside the method.
This wont be possible. Reason being, you are trying to render a value whose value is continuously changed by Observable.
Now, when you are trying to read outside
console.log, you get undefined as the value is yet to be set by Observable streams
. Now, when the value is changed ( lets say after 1 sec ), the outer
console.log has already been executed and so you wont see any changes of the this.data
To make monitor the change in it's value, put the function call in the subscribe
block itself.
As per your comment, You can refer this link
ok, but how can i get this value, I want to return boolean based upon the value.
basically I am calling api to check the access token is valid or not. server return the
state
, now based on this state i am trying to return boolean value in canActivate method. here I am calling base api and then in subscribe I am checking state so that I can return boolean based on state@AshishJambhulkar: Rather than checking the state in
canActivate
, you can move that validation logic toBaseService
, lets say:validRouting()
. Now thisvalidRouting()
can be returned itself fromcanActivate
service (since it can return Observable) which will be of typeobservable
. I hope you got my point.