简体   繁体   English

在 canActivate 中进行延迟,直到获取 IP 地址数据

[英]make delay in canActivate till IP address data is fetched

I'm making a guard for my angular application where all users should be redirected to maintenance page except for certain IPs.我正在为我的 angular 应用程序进行保护,在该应用程序中,除某些 IP 外,所有用户都应重定向到维护页面。 I'm getting the client IP address using third party APIs like http://api.ipify.org/?format=json .我正在使用http://api.ipify.org/?format=json等第三方 API 获取客户端 IP 地址。 The PROBLEM I'm facing is that the canActivate guard gets executed before the IP API sends in the response, thus always returning false and then the response gets loaded.我面临的问题是 canActivate 保护在 IP API 发送响应之前执行,因此总是返回 false 然后响应被加载。

canActivate Function可以激活Function

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

Service服务

  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 
  }

You can try returning an observable instead of true / false and filter it so it will fire if conditions are met like:您可以尝试返回 observable 而不是 true / false 并对其进行过滤,以便在满足以下条件时触发:

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

You should implement the return logic at getCanactivateStatus() to get this work您应该在 getCanactivateStatus() 实现返回逻辑来完成这项工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM