美文网首页
00010.HttpInterceptor API Promis

00010.HttpInterceptor API Promis

作者: 笑着字太黑 | 来源:发表于2023-10-16 15:20 被阅读0次
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { tap, switchMap, catchError } from 'rxjs/operators';


  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return this.cognitoUserPool.getCurrentSession().pipe(
      catchError(err => {
        return of(false);
      })
    ).pipe(
      switchMap(res => {
        if (res) {
          req = req.clone({
            withCredentials: true, 
            headers: req.headers.set('Authorization', 'Bearer ' + res.idToken.jwtToken)
          });
        }
        return next.handle(req).pipe(
          tap({
            next: (event) => {
              if (event instanceof HttpResponse) {
                if (event.headers.has('Authorization')) {
                  const authHeaderString = event.headers.get('Authorization');
                  XXXX
                }
              }
            },
            error: (error) => {
              if (error instanceof HttpErrorResponse) {
                if (error.status === 401) {
                  XXXX
                }
              }
            }
          })
        );
      })
    );
  }

相关文章

网友评论

      本文标题:00010.HttpInterceptor API Promis

      本文链接:https://www.haomeiwen.com/subject/yvnxidtx.html