Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting variable data outside subscribe method

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.

like image 623
Ashish Jambhulkar Avatar asked Oct 31 '25 08:10

Ashish Jambhulkar


2 Answers

That won't be possible. The 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. when the value is changed (let's say after 1 sec ), the outer console.log has already been executed and so you won't see any changes of the this.data

For monitoring the change in its value, put the function call in the subscribe block itself.

Update 1

As per your comment, You can refer this link

like image 107
Shashank Vivek Avatar answered Nov 01 '25 21:11

Shashank Vivek


The BaseService.valid returns an Observable which emits after the canActivate method returns.

The console.log after the subscribe block executes first, when this.data is still undefined.

canActivate(
  next: ActivatedRouteSnapshot,
  state: RouterStateSnapshot): boolean {
  // 1.
  var session: any = { token: localStorage.getItem('abc') };   

  this.base.valid(session).subscribe(result => {
    // 3.
    this.data=result;
    console.log(this.data); 
  });


  // 2.
  console.log(this.data); 
  return true;
}
like image 44
Tomasz Kula Avatar answered Nov 01 '25 21:11

Tomasz Kula