Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Angular 中的请求拦截 #121

Open
reng99 opened this issue May 21, 2022 · 0 comments
Open

Angular 中的请求拦截 #121

reng99 opened this issue May 21, 2022 · 0 comments
Labels
angular blog a single blog

Comments

@reng99
Copy link
Owner

reng99 commented May 21, 2022

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第6天,点击查看活动详情

在上一篇的文章 Angular 中使用 Api 代理,我们处理了本地联调接口的问题,使用了代理。

我们的接口是单独编写的处理的,在实际的开发项目中,有众多的接口,有些需要登陆凭证,有些不需要。一个一个接口处理不妥,我们是否可以考虑对请求进行拦截封装呢?

本文章来实现下。

区分环境

我们需要对不同环境下的服务进行拦截。在使用 angular-cli 生成项目的时候,它已经自动做好了环境的区分,在 app/enviroments 目录下:

environments                                          
├── environment.prod.ts                  // 生产环境使用的配置
└── environment.ts                       // 开发环境使用的配置

我们对开发环境进行修改下:

// enviroment.ts

export const environment = {
  baseUrl: '',
  production: false
};

baseUrl 是在你发出请求的时候添加在请求的前面的字段,他指向你要请求的地址。我什么都没加,其实等同加了 http://localhost:4200 的内容。

当然,你这里添加的内容要配合你代理上加的内容调整,读者可以自己思考验证

添加拦截器

我们生成服务 http-interceptor.service.ts 拦截器服务,我们希望每个请求,都经过这个服务。

// http-interceptor.service.ts

import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpHandler,
  HttpInterceptor, // 拦截器
  HttpRequest, // 请求
} from '@angular/common/http';

import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

import { environment } from 'src/environments/environment';

@Injectable({
  providedIn: 'root'
})
export class HttpInterceptorService implements HttpInterceptor {

  constructor() { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let secureReq: HttpRequest<any> = req;

    secureReq = secureReq.clone({
      url: environment.baseUrl + req.url
    });

    return next.handle(secureReq).pipe(
      tap(
        (response: any) => {
          // 处理响应的数据
          console.log(response)
        },
        (error: any) => {
          // 处理错误的数据
          console.log(error)
        }
      )
    )
  }
}

要想拦截器生效,我们还得在 app.module.ts 上注入:

// app.module.ts

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
// 拦截器服务
import { HttpInterceptorService } from './services/http-interceptor.service';

providers: [
  // 依赖注入
  {
    provide: HTTP_INTERCEPTORS,
    useClass: HttpInterceptorService,
    multi: true,
  }
],

验证

到这里,我们已经成功的实现了拦截器。如果你运行 npm run dev,你会在控制台上看到下面的信息:

拦截器-response.png

想要验证是否需要内容凭证才能访问内容,这里我使用了 [post] https://jimmyarea.com/api/private/leave/message 的接口尝试,得到如下错误:

接口-401.png

后端已经处理这个接口需要凭证才可以进行操作,所以直接报错 401

那么,问题来了。我们登陆之后,需要怎么带上凭证呢?

如下,我们修改下拦截器内容:

let secureReq: HttpRequest<any> = req;
// ...
// 使用 localhost 存储用户凭证,在请求头带上
if (window.localStorage.getItem('ut')) {
  let token = window.localStorage.getItem('ut') || ''
  secureReq = secureReq.clone({
    headers: req.headers.set('token', token)
  });
}

// ...

这个凭证的有效期,需要读者进入系统的时候,判断一下有效期是否有效,再考虑重置 localstorage 的值,不然会一直报错,这个也是很简单,对 localstorage 进行相关的封装方便操作即可~

【完】✅

@reng99 reng99 added angular blog a single blog labels Jun 20, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
angular blog a single blog
Projects
None yet
Development

No branches or pull requests

1 participant