Ionic 4、Angular 8 和 HTTP 拦截器 [英] Ionic 4, Angular 8 and HTTP interceptor

查看:31
本文介绍了Ionic 4、Angular 8 和 HTTP 拦截器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Ionic 4 和 Angular 8 构建移动应用程序,但我的 HTTP 拦截器无法正常工作.我在这里查看了拦截器的所有示例,但没有一个适合我的需要,或者根本不再起作用.

I'm building mobile app with Ionic 4 and Angular 8 and can't make my HTTP interceptor working. I reviewed all the examples of interceptors here but none fits my need or simply do not work any more.

与常规 Angular 8 版本的唯一区别是从存储读取令牌的第一行.原始的 Angular 8 代码同步读取这些东西并且不需要订阅因此它可以工作.这里是 Ionic 存储,它以异步方式调用本地资源.

The only difference against the regular Angular 8 version is the first line where token is read from the storage. Original Angular 8 code reads such things synchronously and doesn't need subscription thus it works. This one here is Ionic storage which calls local resources in async way.

这是我的代码:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  from(this.storage.get('id_token')).subscribe(res => {
    const idToken = res;
    if (idToken) {
      const cloned = req.clone({ headers: req.headers.set('token', idToken)});
      return next.handle(cloned);
    } else {
      console.log('Unauthorized calls are redirected to login page');
      return next.handle(req).pipe(
        tap(
          event => {
            // logging the http response to browser's console in case of a success
            if (event instanceof HttpResponse) {
              // console.log('api call success :', event);
            }
          },
          error => {
            // logging the http response to browser's console in case of a failure
            if (error instanceof HttpErrorResponse) {
              if (error.status === 401) {
                this.router.navigateByUrl('/');
              }
            }
          }
        )
      );
    }
  });
}

以这种形式编译,但我的 IDE 报告:TS2355(函数必须返回一个值).这里有什么问题或缺失?我想不通.

In this shape it compiles but my IDE reports: TS2355 (function has to return a value). What is wrong or missing here ? I can't figure it out.

推荐答案

好的,看来您正在尝试在 1 个拦截器中做 2 件事:

Ok, so it looks like you're trying to do 2 things in 1 interceptor:

  • 添加不记名令牌
  • 如果错误代码是 401 - 重定向到主页

此外,您将在每次请求时访问存储空间,这很昂贵.

Also, you'll access the storage at EVERY request which is expensive.

这是我所做的:

  • 创建一个身份验证服务并在那里管理令牌
  • 在身份验证服务中有一个 BehaviourSubject 存储令牌的最后一个值

这里是:

// JWT interceptor
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';

import { AuthenticationService } from '../services/authentication.service';


@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    constructor(private authenticationService: AuthenticationService) {}

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // add authorization header with jwt token if available
        const currentAuthToken = this.authenticationService.currentAuthTokenValue;
        if (currentAuthToken && currentAuthToken.token) {
            const headers = {
                'Authorization': `Bearer ${currentAuthToken.token}`,
            };
            if (request.responseType === 'json') {
                headers['Content-Type'] = 'application/json';
            }
            request = request.clone({
                setHeaders: headers
            });
        }

        return next.handle(request);
    }
}

authenticationService.currentAuthTokenValue 只是一个返回当前主题值的 getter

authenticationService.currentAuthTokenValue is just a getter that returns current subject's value

public get currentAuthTokenValue(): AuthToken {
    return this.currentAuthTokenSubject.value;
}

还有另一个错误拦截器:

Also another interceptor for error:

// Error interceptor
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

import { AuthenticationService } from '../services/authentication.service';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
    constructor(private authenticationService: AuthenticationService) {}

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(catchError(err => {
            if (err.status === 401) {
                // auto logout if 401 response returned from api
                this.authenticationService.logout().then(() => {
                    location.reload();
                });
            }

            const error = err.error.message || err.error.detail || err.statusText;
            return throwError(error);
        }));
    }
}

希望有帮助.

这篇关于Ionic 4、Angular 8 和 HTTP 拦截器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆