我正在尝试使用Ionic 4项目中的HttpInterceptor对所有对后端的API调用进行身份验证。令牌通过NativeStorage保存。我拨打登录电话时出现问题。由于还没有可用的令牌,NativeStorage返回一个错误,中断该链:NativeStorageError {code:2,source:“ Native”,异常:null}

httpConfig.interceptor.ts

import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpResponse,
  HttpErrorResponse
} from '@angular/common/http';

import { Observable, throwError, from } from 'rxjs';
import { map, catchError, switchMap } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import { LoadingController } from '@ionic/angular';
import { NativeStorage } from '@ionic-native/native-storage/ngx';

const TOKEN_KEY = 'auth-token';

@Injectable()
export class HttpConfigInterceptor implements HttpInterceptor {
  loaderToShow: any;
  loadingPresent = false;
  debug = false;
  constructor(
    public loadingController: LoadingController,
    private storage: NativeStorage
  )
  { }

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

      return from(this.storage.getItem(TOKEN_KEY))
        .pipe(
          switchMap(token => {
            if (token) {
                request = request.clone({ headers: request.headers.set('Authorization', 'Bearer ' + token.access_token) });
            }
            if (!request.headers.has('Content-Type')) {
              request = request.clone({ headers: request.headers.set('Content-Type', 'application/json') });
            }

            this.showLoader();

            return next.handle(request).pipe(

              map((event: HttpEvent<any>) => {
                if (event instanceof HttpResponse) {
                  console.log('event--->>>', event);
                }
                this.hideLoader();
                return event;
              }),
              catchError((error: HttpErrorResponse) => {
                this.hideLoader();
                return throwError(error);
              })
            );

          })
        );
  }

  showLoader() {
    console.log("show loader");
    this.loaderToShow = this.loadingController.create({
      message: 'Cargando datos...'
    }).then((res) => {

      this.loadingPresent = true;
      res.present();

      res.onDidDismiss().then((dis) => {
        console.log('Loading dismissed!');
      });
    });
  }

  hideLoader() {
    if(this.loadingPresent) {
      this.loadingController.dismiss();
      this.loadingPresent = false;
    }
  }
}


身份验证服务

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Platform } from '@ionic/angular';
import { tap, map } from 'rxjs/operators';
import { NativeStorage } from '@ionic-native/native-storage/ngx';
import { environment } from '../../environments/environment';
import { User } from '../models/user';
import { BehaviorSubject } from 'rxjs';

const TOKEN_KEY = 'auth-token';

@Injectable({
  providedIn: 'root'
})

export class AuthService {
  isLoggedIn = false;
  token:any;

  authenticationState = new BehaviorSubject(false);

  constructor(
    private http: HttpClient,
    private storage: NativeStorage,
    private plt: Platform
  )
  {
    this.plt.ready().then(() => {
      this.checkToken();
    });
  }

  login(login: String, password: String) {
    return this.http.post(environment.API_URL + 'auth/login',
      { login: login, password: password }
    ).pipe(
        map(token => {
          this.storage.setItem(TOKEN_KEY, token)
          .then(
            () => {
              this.authenticationState.next(true);
            },
            error => console.error('Error storing item', error)
          );
        }),
    );
  }

  logout() {
    return this.http.get(environment.API_URL + 'auth/logout')
    .pipe(
      tap(data => {
        return this.storage.remove(TOKEN_KEY).then(() => {
          this.authenticationState.next(false);
        });
      })
    )
  }

  isAuthenticated() {
    return this.authenticationState.value;
  }


  checkToken() {
    this.storage.getItem(TOKEN_KEY).then(res => {
      if (res) {
        this.authenticationState.next(true);
      }
    });
  }
}


第一次尝试登录时,它会通过拦截器返回NativeStorage的“找不到令牌”错误
NativeStorageError {代码:2,来源:“本机”,异常:空}

最佳答案

当项目不存在时,您尝试访问'TOKEN_KEY'项目。

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
   return from(this.storage.getItem(TOKEN_KEY)) <-- //This causes error


要么

checkToken() {
  this.storage.getItem(TOKEN_KEY).then(res => { <-- //This causes error
    if (res) {
       this.authenticationState.next(true);
    }
  });
}


您必须为'TOKEN_KEY'初始化默认值,或者添加其他条件来控制(检查)令牌

您可以使用this.storage.keys列表查找密钥

其他错误代码:


NATIVE_WRITE_FAILED = 1
ITEM_NOT_FOUND = 2
NULL_REFERENCE = 3
UNDEFINED_TYPE = 4
JSON_ERROR = 5
WRONG_PARAMETER = 6

关于javascript - ionic 4 + HttpInterceptor + token ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58506189/

10-12 14:09