Angular 4.3 HttpClient : Intercept response

后端 未结 4 1180
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 12:59

In the documentation about the new HttpClientModule included in the new version of Angular 4.3, the mechanism to intercept requests is explained very well. Ther

4条回答
  •  一生所求
    2020-12-02 13:19

    I suppose you can use do as @federico-scamuzzi suggested, or you can use map and catch like so:

    import { Injectable } from '@angular/core';
    import {
      HttpErrorResponse,
      HttpEvent,
      HttpHandler,
      HttpInterceptor,
      HttpRequest,
      HttpResponse
    } from '@angular/common/http';
    
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/catch';
    import 'rxjs/add/observable/throw';
    
    @Injectable()
    export class AuthInterceptor implements HttpInterceptor {
      intercept(req: HttpRequest, next: HttpHandler): Observable> {
        console.info('req.headers =', req.headers, ';');
        return next.handle(req)
          .map((event: HttpEvent) => {
            if (event instanceof HttpResponse && ~~(event.status / 100) > 3) {
              console.info('HttpResponse::event =', event, ';');
            } else console.info('event =', event, ';');
            return event;
          })
          .catch((err: any, caught) => {
            if (err instanceof HttpErrorResponse) {
              if (err.status === 403) {
                console.info('err.error =', err.error, ';');
              }
              return Observable.throw(err);
            }
          });
      }
    }
    

    EDIT: @LalitKushwah was asking about redirecting if(!loggedIn). I use Route Guards, specifically:

    import { Injectable } from '@angular/core';
    import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot
           } from '@angular/router';
    
    import { Observable } from 'rxjs/Observable';
    
    import { AuthService } from '../../api/auth/auth.service';
    import { AlertsService } from '../alerts/alerts.service';
    
    @Injectable()
    export class AuthGuard implements CanActivate {
      constructor(private router: Router,
                  private alertsService: AlertsService) {}
    
      canActivate(next: ActivatedRouteSnapshot,
                  state: RouterStateSnapshot
                  ): Observable | Promise | boolean {
        if (AuthService.loggedIn()) return true;
    
        const url: string = state.url;
    
        this.alertsService.add(`Auth required to view ${url}`);
        this.router
          .navigate(['/auth'], { queryParams: { redirectUrl: url } })
          .then(() => {});
        return false;
      }
    }
    

    Then I can simply add that as an argument to my route:

    {
      path: 'dashboard', loadChildren:'app/dashboard/dashboard.module#DashboardModule',
      canActivate: [AuthGuard]
    }
    

提交回复
热议问题