【问题标题】:Angular HttpClient Post with AuthGuard doesnt work带有 AuthGuard 的 Angular HttpClient Post 不起作用
【发布时间】:2019-02-26 13:43:18
【问题描述】:

我有以下问题; Observable 总是返回 undefined。 我想我真的不明白我需要如何使用 HttpClient 来使用 AuthGuard。

canActivate(
  next: ActivatedRouteSnapshot,
  state: RouterStateSnapshot): Observable < boolean > {
  var bool
  var token = localStorage.getItem('Authorization');
  if (token != null) {
    this.http.post('http://localhost:5000/v1/logstatus?token=' + token, this.authData).subscribe(res => {
      if (!JSON.stringify(res).includes('AuthorizationNotFound')) {
        bool = true
      } else {
        bool = false
      }
    })
  } else {
    bool = false
  }
  console.log(bool)
  return observableOf(bool)
}

【问题讨论】:

    标签: javascript angular post httpclient


    【解决方案1】:

    this.http.post 是一个异步操作,因此您在bool 由结果定义之前返回of(bool)。换句话说,of(bool) 甚至在 POST 完成之前就被解析并设置了 bool 的值。

    相反,您可以将可观察到的响应map 响应为布尔值并直接返回。将您的 if 块更改为:

    if (token != null) {
      return this.http.post('http://localhost:5000/v1/logstatus?token=' + token, this.authData)
                 .map(res => !JSON.stringify(res).includes('AuthorizationNotFound'));
    }
    

    这将使 POST observable 直接映射到您要查找的布尔值。

    不相关,但如果您还没有这样做,您应该考虑在此调用中添加错误处理逻辑,因为如果 POST 调用失败,您的守卫将中断。

    【讨论】:

    • 您好,感谢您的快速回复!它适用于: if(token != null){ return this.http.post('localhost:5000/v1/ts_p/logstatus?token=' + token, this.authData) .pipe(map(res => !JSON.stringify(res).includes(' AuthorizationNotFound'))); }
    猜你喜欢
    • 1970-01-01
    • 2018-10-18
    • 2020-06-20
    • 1970-01-01
    • 2023-03-29
    • 2019-05-22
    • 1970-01-01
    • 2021-01-11
    相关资源
    最近更新 更多