简体   繁体   English

如何返回 Observable<boolean> 在 Angular 6 中的受保护路线上的 canActivate

[英]How to return Observable<boolean> in canActivate on a guarded route in Angular 6

I would like to guard a route with a CanActivate class.我想用 CanActivate 类保护路线。 The documentation I have read always has the canActivate method returning a boolean value, but I think I need to return either Observable or Promise.我读过的文档总是有返回布尔值的canActivate方法,但我认为我需要返回 Observable 或 Promise。

My app has a data store with a property user that is an Observable<User> .我的应用程序有一个数据存储,其属性userObservable<User>

When the app loads, user.role is undefined .当应用加载时, user.role 是undefined After an initial http request, the user.role becomes either "user" or "guest".在初始 http 请求之后,user.role 变为“user”或“guest”。 So, I need the canActivate method to wait until user.role is set to either "user" or "guest", then respond.因此,我需要 canActivate 方法等待 user.role 设置为“user”或“guest”,然后响应。 Here is what I have now:这是我现在所拥有的:

  canActivate(): Observable<boolean> {
    return new Observable((observer: Observer<boolean>): void => {
      this.state.user.subscribe((user: User) => {
        if (user.role === 'user') {
          observer.next(true);
        } else if (user.role === 'guest') {
          observer.next(false);
          this.router.navigate(['/login']);
        }
        // user is not set, wait for next value
      });
    });
  }

The problem I think is that the subscription keeps going, and my router is sometimes unexpectedly redirected when state.user is updated.我认为的问题是订阅一直在进行,当 state.user 更新时,我的路由器有时会意外重定向。 How can I fix this.我怎样才能解决这个问题。 Or, is there a better way to do this?或者,有没有更好的方法来做到这一点?

Why you want to hang this observable if user.role is undefined ? 如果user.role undefined为什么要挂起这个可观察的user.role In this way whole router is hanging. 这样,整个路由器就挂起了。 This may cause unexpected behavior like unwanted redirects. 这可能会导致意外的行为,例如不需要的重定向。

I think you shouldn't hang this canActivate() method but return true or false as fast as possible in async way. 我认为您不应该挂此canActivate()方法,而应以异步方式尽快返回truefalse

I don't know context of the problem. 我不知道问题的背景。 If you want to make sure user is authorized before running the application maybe better use APP_INITIALIZER ? 如果要在运行应用程序之前确保用户已被授权,最好使用APP_INITIALIZER This mechanism will "hang" whole application until some important things are done and resolve Promise . 这种机制将“挂起”整个应用程序,直到完成一些重要的事情并解决Promise为止。

Can you try this piece of code 你能试一下这段代码吗

canActivate(): Observable<boolean> {
    return this.state.user.map((user: User) => {
        if (user.role === 'user') {
          return true;
        } else if (user.role === 'guest') {
          this.router.navigate(['/login']);
          return false;
        }
        // user is not set, wait for next value
      });
  }

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

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