【问题标题】:Angular Auth Guard with a Promise and if statement带有 Promise 和 if 语句的 Angular Auth Guard
【发布时间】:2021-09-03 12:37:51
【问题描述】:

我想使用守卫来决定用户是否可以导航到登录页面,但我知道我的逻辑是错误的,因为Promise。 请参阅下面的代码。

  canActivate(): boolean | Observable<boolean> | Promise<boolean> {
    if (!this.localStorage.getObject('isInitialized')) {
      this.router.navigate(['/locaties']);
      return true;
    }
    return false;
  }

我知道我在做什么是错误的,但我缺乏关于解决这个问题的承诺的知识。我需要做什么才能完成这项工作?

这是我的localstorage.getObject()

  // Returns object
  async getObject(key: string) {
    const ret = await Storage.get({ key: key });
    return JSON.parse(ret.value);
  }

【问题讨论】:

    标签: angular typescript if-statement promise auth-guard


    【解决方案1】:

    如果你想在你的 can activate 方法中使用基于异步结果的条件,那么你可以使用 Promise。如果您打算使用本地存储中的直接值,则无需使用 promise。您可以执行以下操作来使用 Promise...

      canActivate(): boolean | Observable<boolean> | Promise<boolean> {
        return new Promise(() => {
        if (!this.localStorage.getObject('isInitialized')) {
          this.router.navigate(['/locaties']);
          // Do not allow the route
          resolve(false);
        } else {
          // Allow the route
          resolve(true);
         }
        
        });
      }
    

    【讨论】:

      【解决方案2】:

      答案是

          this.localStorage.getObject('isInitialized').then((res) => {
            if (res == true) {
              this.router.navigate(['/locaties']);
              return false;
            }
          });
          return true;
        }
      

      必须记住,当用户想要导航到页面时会触发身份验证保护。没有必要让它比这更复杂

      【讨论】:

        【解决方案3】:

        所以这里有一些问题,但我不认为承诺是其中之一。您的函数签名表明您可以选择返回三种类型之一,

        canActivate(): boolean | Observable<boolean> | Promise<boolean>
        

        但你只返回一个布尔值,所以你真的可以重写这个,

        canActivate(): boolean
        

        但这不是问题。没有看到您的路线设置很难说,但是如果他们请求的路线是允许的并且没有必要,您似乎正在重新路由用户。当用户已经尝试导航到一个页面时,路由守卫就会运行。如果路由守卫返回 true,则允许进行导航,并且用户将继续访问路由守卫所保护的任何页面。

        但是当路由保护返回 false 时,您应该指定重定向页面。换句话说,当用户无法访问守卫背后的页面时,你想将他们发送到哪里?

        一般来说,看起来像这样,

        @Injectable()
        export class AuthGuard implements CanActivate {
            constructor(private router: Router) {}
        
            canActivate(state: RouterStateSnapshot): boolean {
                if (!this.localStorage.getObject('isInitialized')) {
                    //No need to route here, user will be taken to the route they were trying access
                    return true;
                } else {
                    //Send the user back to the '/anotherpage' path if they are not logged in
                    this.router.navigate(['/anotherpage']);
                    return false;
                }
            }
        }
        

        然后在这样的地方定义你的路线,

        export const appRoutes: Routes = [
            {
                path: 'pageProtectedByAuthGuard',
                component: YourComponent,
                canActivate: [AuthGuard]
            }
        ];
        

        然后在你的模块中你需要导入这些路由,

        @NgModule({
            imports: [RouterModule.forRoot(appRoutes, { enableTracing: false })],
            ...
        })
        

        更多关于 CanActivate 的信息在这里:https://angular.io/api/router/CanActivate

        【讨论】:

        • 我已经按照你说的实现了。我之前在其他几个页面上做过(以防止用户在填写表格时离开)。如果 localstorage.getObject() 返回 true(这意味着用户已通过身份验证),我需要它将用户重定向到不同的页面。因此,即使用户未通过身份验证,它仍然会执行语句的 else 部分并重定向用户。我似乎无法理解这个
        猜你喜欢
        • 2017-10-18
        • 2019-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-16
        • 1970-01-01
        • 2016-09-07
        相关资源
        最近更新 更多