【发布时间】:2020-06-04 22:18:21
【问题描述】:
我正在 Angular 中创建一个 Route Guard;它的运作方式取决于您是否与公司有关联;它会将您发送到特定组件。 Unfourtnetly,当运行 canLoad 方法时,它不会保存 companylist 变量的值。任何帮助将不胜感激!
import { Injectable } from '@angular/core';
import { CanActivate, Router, CanLoad } from '@angular/router';
import { AuthService } from 'src/app/auth.service';
import { User } from 'src/models/user';
import {ListdataService} from 'src/app/listdata.service';
@Injectable({
providedIn: 'root'
})
export class CompanyonlyService implements CanActivate, CanLoad {
companieslist=[];
constructor(private authService: AuthService, private router: Router,private dataService:ListdataService) { }
run(){
this.dataService.sendGetRequestcompanies().subscribe((data: any[])=>{
let tmp = [];
for (let key in data)
if (data.hasOwnProperty(key))
tmp.push(data[key])
this.companieslist = tmp;
console.log(this.companieslist)
} )}
canActivate() {
return this.canLoad()
}
//this method won't set the value of the variable why?
canLoad(){
this.run()
console.log('after loop')
console.log(this.companieslist)
if (this.companieslist.length==0) {
this.router.navigate(['/companysignup']);
}
else{
this.router.navigate(['/dashboard']);
}
return this.authService.isLoggedIn();
}
}
[在此处输入图像描述]这是我在控制台中返回的内容
【问题讨论】:
-
我在控制台中返回的是在 run() 之后包含一个项目的数组。然后当我 console.log(this.companieslist) 我返回一个空数组
-
因为 canLoad 内部的 console.log(this.companieslist) 在可观察到的发射值之前评估并填充数组。 js是异步的
标签: angular angular-router-guards angular-route-guards