我正在 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();
}
}
[在此处输入图像描述]这是我在控制台中返回的内容