4

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.

4

4 回答 4

7

那是不可能的。原因是,您试图呈现一个值,其值被 Observable 不断更改。

现在,当您尝试读取outside console.log时,您会得到 undefined ,因为该值尚未由 Observable 设置streams。当值改变时(比如说 1 sec 之后),outerconsole.log 已经被执行,所以你不会看到任何改变this.data

要监视其值的变化,请将函数调用放在subscribe块本身中。

更新 1

根据您的评论,您可以参考此链接

于 2018-04-10T09:42:26.370 回答
1

返回一个 Observable ,它在方法返回BaseService.valid后发出。canActivate

console.logafter subscribe 块首先执行,when仍然this.data未定义。

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;
}
于 2018-04-10T09:32:38.123 回答
0

为了能够将数据推送到您定义的数组,首先您必须将其初始化为一个空数组,因此:

代替 :

data:Array<Object>

尝试这个:

data: Array<any> = new Array<any>();

这是我用的,希望对你有帮助。

于 2020-01-31T10:35:50.153 回答
0
public new_data:any=[];
this.base.valid(session).subscribe(result => {
  this.data=result;
  for(let data of this.data) {
    this.new_data.push(id:data.id, name:data.name)
  }
    console.log(this.new_data); <-- first
});
 console.log(this.new_data); <-- Second
于 2019-07-18T11:24:38.670 回答