Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用AuthGuard的Angular8 canActivate方法中的API验证令牌_Javascript_Angular_Async Await_Es6 Promise_Auth Guard - Fatal编程技术网

Javascript 使用AuthGuard的Angular8 canActivate方法中的API验证令牌

Javascript 使用AuthGuard的Angular8 canActivate方法中的API验证令牌,javascript,angular,async-await,es6-promise,auth-guard,Javascript,Angular,Async Await,Es6 Promise,Auth Guard,我想对某些路由的每个刷新请求进行一些验证。所以我使用AngularAuthGuard。问题出在canActivate方法中,我想用在线API执行验证 API是/token/verify,它只获取token变量(jwt)并验证它是真是假。 如果验证未完成,则将发送到/login页面,否则执行其余操作 代码如下: canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean&g

我想对某些路由的每个刷新请求进行一些验证。所以我使用Angular
AuthGuard
。问题出在
canActivate
方法中,我想用在线API执行验证

API是
/token/verify
,它只获取
token
变量(jwt)并验证它是真是假。 如果验证未完成,则将发送到
/login
页面,否则执行其余操作

代码如下:

canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
let token = this.auth.getToken();
let url = '/token/verify/';
if (!token) {
  this.router.navigate(['/login']);
  return false;
}
this.auth.verifyToken().then(res => {
  return true;
}).catch(err => {
  this.router.navigate(['/login']);
  return false;
})
问题是
promise
调用不起作用,将被传递。我的意思是,从localstorage进行检查的第一部分工作正常。但是下一个用在线API检查它的部分将不起作用。而且,
authGuard
不会等待其响应来执行路由


我想应该是以某种
async/await
的方式。但是我做了一些测试,没有一个有效。如果有人能帮助我,我将非常高兴。

我认为如果您使用
可观察的
s,您将能够简化整个实现

如果你考虑了这个建议,那么你的 ValuyToMtUs/Cuff>方法可以重构为:

import { of, Observable } from 'rxjs';

verifyToken(): Observable<boolean> {
  const token = this.getToken();
  return token ? this.http
    .post(this.url + '/token/verify/', {
      'token': token
    })
    .pipe(
      tap(res => localStorage.data = JSON.stringify(res)),
      map(
        res => true,
        error => false
      )
    ) : of(false)
}
import{of,Observable}来自'rxjs';
verifyToken():可观察{
const token=this.getToken();
返回令牌?this.http
.post(this.url+'/token/verify/'{
“令牌”:令牌
})
.烟斗(
点击(res=>localStorage.data=JSON.stringify(res)),
地图(
res=>正确,
错误=>false
)
):of(假)
}
然后,在你的守卫下,你只需这样做:

canActivate(
  next: ActivatedRouteSnapshot,
  state: RouterStateSnapshot
): Observable < boolean > | Promise < boolean > | boolean {
  const token = this.auth.getToken();
  const url = "/token/verify/";

  if (!token) {
    this.router.navigate(['/login']);
    return false;
  }

  return this.auth.verifyToken().pipe(
    catchError(err => {
      console.log('Handling error locally and rethrowing it...', err);
      this.router.navigate(['/login']);
      return of(false);
    })
  );

}
canActivate(
下一步:ActivatedRouteSnapshot,
状态:RouterStateSnapshot
):可观察的|承诺| boolean{
const token=this.auth.getToken();
const url=“/token/verify/”;
如果(!令牌){
this.router.navigate(['/login']);
返回false;
}
返回此.auth.verifyToken()管道(
catchError(err=>{
log('本地处理错误并重新引用它…',err);
this.router.navigate(['/login']);
归还(假);
})
);
}

这是给你的裁判的一封信


感谢您花时间写下详细的回复。但是您可以检查canActivate last
return
语句吗。这似乎需要一些改变。它给出了此错误
参数类型MonotypeOperator函数不可赋值…
请再次检查。@RezaTorkamanAhmadi,请尝试更新的答案。我已经将
if
条件置于
{}
No中,仍然是相同的错误。我不应该使用
管道
捕获
方法吗?@RezaTorkamanAhmadi,很抱歉。我已经用正确的代码和示例工作演示更新了我的答案,以供参考。请检查这是否有帮助。我也能够使用
catchError
使其工作。也请验证我的更改。非常感谢。在你的帮助下,我解决了这个问题
canActivate(
  next: ActivatedRouteSnapshot,
  state: RouterStateSnapshot
): Observable < boolean > | Promise < boolean > | boolean {
  const token = this.auth.getToken();
  const url = "/token/verify/";

  if (!token) {
    this.router.navigate(['/login']);
    return false;
  }

  return this.auth.verifyToken().pipe(
    catchError(err => {
      console.log('Handling error locally and rethrowing it...', err);
      this.router.navigate(['/login']);
      return of(false);
    })
  );

}