Ionic 4,Angular 8和HTTP拦截器

时间:2019-12-04 08:27:21

标签: ionic4 angular8

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

与常规Angular 8版本的唯一区别是从存储读取令牌的第一行。原始的Angular 8代码可以同步读取此类内容,不需要订阅,因此可以正常工作。这里是离子存储,它以异步方式调用本地资源。

这是我的代码:

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(函数必须返回一个值)。 这里有什么问题或遗漏?我不知道。

1 个答案:

答案 0 :(得分:1)

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

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

此外,您会在每次请求时访问存储,这很昂贵。

这就是我所做的:

  • 创建身份验证服务并在那里管理令牌
  • 在身份验证服务中,有一个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只是一个获取当前主题值的吸气剂

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

另一个错误拦截器:

// 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);
        }));
    }
}

希望有帮助。