延迟 canActivate 直到获取 IP 地址数据

问题描述

我正在为我的 angular 应用程序做一个保护,所有用户都应该被重定向到维护页面,除了某些 IP。我使用 http://api.ipify.org/?format=json 等第三方 API 获取客户端 IP 地址。我面临的问题是 canActivate 守卫在 IP API 发送响应之前被执行,因此总是返回 false,然后响应被加载。

canActivate 函数

  canActivate(): boolean | Observable<boolean> {
    if (this.globalService.getCanactivateStatus()) {
      return true;
    } else {
      this._router.navigate(["/en/maintainance"]);
      return false;
    }
  }

服务

  getUserIp() {
    this.http.get<{ ip: string }>("http://api.ipify.org/?format=json").subscribe((data) => {
      this.clientIP = data.ip;
    });
  }

  getCanactivateStatus() {
    this.getUserIp()
      if (this.maintainance_status) {
        if (this.IpArray.indexOf(this.clientIP) !== -1) { //this.clientIP waits for response while canactivated gets executed
          return true
         }
      } else return true 
  }

解决方法

您可以尝试返回一个 observable 而不是 true / false 并对其进行过滤,以便在满足以下条件时触发:

return this.globalService.getCanactivateStatus()
        .pipe(
          filter((status) => !!status),take(1)
        )

您应该在 getCanactivateStatus() 中实现返回逻辑以完成这项工作