【问题标题】:How to get the Bearer Auth token before sending the request using HttpInterceptor in Ionic 4如何在 Ionic 4 中使用 HttpInterceptor 发送请求之前获取 Bearer Auth 令牌
【发布时间】:2019-07-07 18:48:59
【问题描述】:

我使用 Ionic 4 创建应用程序。我尝试实现一个 HttpInterceptor 来将承载授权令牌添加到请求中。

问题:在读取令牌之前发送请求

更多细节:

  1. 我尝试从本地存储中读取令牌
  2. 下面的console.log打印出token

怎么了?

import {HttpRequest,HttpHandler,HttpEvent,HttpInterceptor,HttpResponse,HttpErrorResponse} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { Router } from '@angular/router';
import { Storage } from '@ionic/storage';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

    token:any;

    constructor(private router: Router,private storage: Storage) {
        this.storage.get('User').then((val) => {
            this.token = val;
            console.log(val); // Returns the token
        });
    }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

      console.log(this.token); // Returns undefined
      if (this.token) {
        request = request.clone({
          setHeaders: {
            'Authorization': this.token
          }
        });
      }

      if (!request.headers.has('Content-Type')) {
        request = request.clone({
          setHeaders: {
            'content-type': 'application/json'
          }
        });
      }

      request = request.clone({
        headers: request.headers.set('Accept', 'application/json')
      });

      return next.handle(request).pipe(
        map((event: HttpEvent<any>) => {
          if (event instanceof HttpResponse) {
            console.log('event--->>>', event);
          }
          return event;
        }),
        catchError((error: HttpErrorResponse) => {
          if (error.status === 401) {
            if (error.error.success === false) {
              // this.presentToast('Login failed');
            } else {
              this.router.navigate(['/']);
            }
          }
          return throwError(error);
        }));
    }

}

【问题讨论】:

  • 我很好奇,如果你在构造函数和拦截函数中都放了一个console.log('{CODE_LOCATION}' + this.token),那会返回你的token吗?
  • @dmoore1181 它为构造函数返回它,但它在拦截函数中未定义。我更新了问题。
  • 我只是简单地建议对所有 http 请求使用高级 http 插件。 ionicframework.com/docs/native/http

标签: javascript angular typescript ionic-framework ionic4


【解决方案1】:

对存储的调用返回一个 Promise,因此是异步的。在拦截函数中获取令牌。由于拦截函数需要一个 Observable,所以用 RxJS 转换存储调用:

import { from } from 'rxjs';
import { mergeMap } from "rxjs/operators";

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {


    return from(this.storage.get('User')).pipe(
        mergeMap((val) => {
            // clone and modify the request
            request = request.clone({
                setHeaders: {
                    Authorization: val
                }
            });
            [...more stuff you want]
            return next.handle(request);
        });
     )
}

我没有测试这个功能,但我希望你能明白。也许添加一个 if else 语句和令牌作为局部变量,以便每次调用都不会从存储中读取它。

token:string;
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    if(!this.token)
    return from(this.storage.get('User')).pipe(
        mergeMap((val) => {
            this.token = val
            [... modify and return request headers like above]
        })
    )
    else{ 
        [... use this.token for headers ]
    }
}

【讨论】:

  • 我得到 Object(...)(...).mergeMap is not a function 并且 Property mergeMap 在 Observable 类型上不存在
  • @LucienDubois 抱歉,这是针对较旧的 rxjs 版本。我更新了 rxjs 6 的答案。在这种情况下你必须使用 .pipe(mergeMap(...))
猜你喜欢
  • 2016-06-07
  • 1970-01-01
  • 2018-04-19
  • 2018-11-07
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-05
  • 2018-06-09
相关资源
最近更新 更多