首页 文章

在使用Angular2 Guards执行canActivate之前,如何从服务响应中获取数据

提问于
浏览
3

我正在尝试实现一个防护,检查用户是否在访问视图之前保存了某些配置参数 . 配置表单和我要保护的视图都是分开的 .

为此,我一直在尝试从服务(后端API)获取配置参数,因此我能够检查所需的填充是否为空,因此我可以在canActivate方法中返回true或false,并使用路由器导航 .

我已经尝试从Guard类的构造函数和canActivate方法获取响应,但却发现甚至没有调用该服务 . 我也试过用OnInit实现这个类,但没有运气 .

如何在返回值ture或false之前使canActivate方法等待API响应?

先感谢您!

快速编辑 . 我尝试了几件事,包括:

import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';

@Injectable()
export class ConfigurationGuard implements CanActivate{
  constructor(private service: Service) {}
  canActivate(){
    this.service.getConfigParameters().subscribe(parameters => {
      //if parameters are correct return true
      //else return false
    });
  }
}

还尝试过:

import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';

@Injectable()
export class ConfigurationGuard implements CanActivate{
  paramsCheck: boolean
  constructor(private service: Service) {
    this.service.getConfigParameters().subscribe(parameters => {
      //if parameters are correct paramsCheck=true
      //else paramsCheck=false
    });
  }
  canActivate(){
    if(paramsCheck){return true}
    return false
  }
}

并尝试使用ngOnInit

import { Injectable, OnInit } from '@angular/core';
import { CanActivate } from '@angular/router';

@Injectable()
export class ConfigurationGuard implements CanActivate,OnInit {
  paramsCheck: boolean
  constructor(private service: Service) { }
  ngOnInit(){
    this.service.getConfigParameters().subscribe(parameters => {
      //if parameters are correct paramsCheck=true
      //else paramsCheck=false
    });
  }
  canActivate(){
    if(paramsCheck){return true}
    return false
  }
}

这些选项都没有奏效 . 我还尝试了一个服务调用方法,它返回一个布尔值,让我知道它从服务获得的配置中的参数是否正确,但没有骰子 . 我猜测必须在服务器端进行验证?

2 回答

  • 0

    如果获取配置参数的服务返回 observable

    import { Injectable } from '@angular/core';
    import { CanActivate } from '@angular/router';
    
    @Injectable()
    export class CanActivateViaAuthGuard implements CanActivate {
    
      constructor(private service : Service) {}
    
      canActivate() {
        this.service.getConfigurationParameters().subscribe(
            parameters => {
                // if parameters are correct return true
                // else return false
            });
      }
    }
    
  • 0

    您可以使用路由器解析,然后从服务中获取数据,并且路由不会发生,直到从服务中获取所有数据 . 请查看此链接以获取Router resolve的演示用法 .

    例如 - https://github.com/rahulrsingh09/footballdetails/blob/master/src/app/team/team.resolve.ts

    请找到我给出类似问题的答案的链接

    Get the value returned by canActivate Method in Angular2 Route in a component?

    这是我使用路由器解析的回购

相关问题