首页 > 解决方案 > 在 canActivate 中进行延迟,直到获取 IP 地址数据

问题描述

我正在为我的 Angular 应用程序做一个保护,除了某些 IP,所有用户都应该被重定向到维护页面。我正在使用第三方 API 获取客户端 IP 地址,例如http://api.ipify.org/?format=json. 我面临的问题是 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 
  }

标签: angularangular-routercanactivateangular-guards

解决方案


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

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

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


推荐阅读