简体   繁体   English

如何在 Angular 9 中实现 CanActivate 的警卫中使用 http 请求的结果?

[英]How can I use the result of an http request in a guard implementing CanActivate in Angular 9?

In angular I have an authguard class that implements canActivate.在 angular 中,我有一个实现 canActivate 的 authguard class。 It must return boolean |它必须返回 boolean | Observable |可观察 | promise etc. I need to call a http.get request to my server that will return either "true" or "false" depending on if user meets a certain condition, to protect certain routes. promise 等。我需要向我的服务器调用 http.get 请求,该请求将根据用户是否满足特定条件返回“true”或“false”,以保护某些路由。

How can I make the http request from the guard, wait for it to return (or timeout?) and use the response to return true or false.如何从警卫发出 http 请求,等待它返回(或超时?)并使用响应返回 true 或 false。 Also how can i handle errors and return false by default?另外我如何处理错误并默认返回false? I know how to use next and error in observable subscribe.我知道如何在可观察订阅中使用下一个和错误。 Other answers have referred to pipe and map but are outdated or don't work.其他答案已提及 pipe 和 map 但已过时或不起作用。

You could return an Obsrvable<boolean> without havnig to subscribe to it.您可以返回Obsrvable<boolean>而无需订阅它。

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
  return this.http.get<boolean>('/auth/authenticated')
    .pipe(
      timeout(10000), // wait for 10 seconds before fail.
      map(x => x), // return the received value true/false
      catchError(() => of(false))
    );
}

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

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