如何使用地图捕获HTTP错误

时间:2019-05-22 15:27:05

标签: angular rxjs

我已经编写了可以访问http api且http返回true | 200或error:unauthorized | 401的防护措施

我可以使用http | 200处理后卫,但在地图中我无法捕获401错误,因此如何在pipe(map())中捕获401

我的警卫密码

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot , Router } from '@angular/router';
import { AuthenticationService } from '../services/authentication.service'
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class IsSigninGuard implements CanActivate {

  constructor( private _auth:AuthenticationService, private router:Router ) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    return this._auth.authState().pipe(
      map(status=>{
        if(!status) { this.router.navigate(['/auth/signin']); return false;}
        return true
      })
    )


  }
}

2 个答案:

答案 0 :(得分:2)

您可以通过以下方式修改代码:

map(status=>{
        if(!status) { this.router.navigate(['/auth/signin']); return false;}
        return true
      }),
catchError((err, caught) => {
          //this you can do what do you want when error
         });

答案 1 :(得分:0)

像这样更改代码:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot , Router } from '@angular/router';
import { AuthenticationService } from '../services/authentication.service'
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class IsSigninGuard implements CanActivate {

  constructor( private _auth:AuthenticationService, private router:Router ) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    return this._auth.authState().pipe(
      map(status=>{
        if(!status) { this.router.navigate(['/auth/signin']); return false;}
        return true
      }), catchError(err => {
           console.log(err);
          // Do some stuff with your error and return Empty Obserable.
          return of([]))
         }))    
  }
}

有关 catchError 的更多信息 here