angular - 角度方法不保存变量的值
问题描述
我正在 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 是异步的,您没有检查请求是否已经完成。
因此,如果在检查条件时请求未完成,companyList 的大小将始终等于 0。
推荐阅读
- c# - 带有特殊中文/阿拉伯字符的 S3 xml 文件下载带有问号而不是字符
- stripe-payments - 无法创建付款意图
- python - 来自bash的Python3无效语法
- r - R - 具有来自另一个数据帧的序列的数据帧
- shell - 如何使用远程实例作为 ssh 端口的“代理”
- python-3.x - Python 3 - 等待所有 .exe 实例关闭,然后再循环打开更多实例
- swift - NSPopover 失去焦点后,NSButton 上的 addCursorRect 失败
- reactjs - 有什么我遗漏的东西,这意味着我只能在本地写入 firestore,而不能使用 Zeit Now 部署的应用程序在生产环境中写入
- python - 找不到网络名称 - 在 Windows 中使用 Python 复制文件
- javascript - 如何使文件在 Node.js 中正确加载