首页 > 解决方案 > 角度方法不保存变量的值

问题描述

我正在 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();
  } 
  }


[在此处输入图像描述]这是我在控制台中返回的内容

标签: angularangular-router-guardsangular-route-guards

解决方案


由于请求,方法 run 是异步的,您没有检查请求是否已经完成。

因此,如果在检查条件时请求未完成,companyList 的大小将始终等于 0。

检查此如何检查所有 HTTP 获取请求是否已完成(已解决) - Angular 2


推荐阅读