本文介绍了如何使用装饰器工厂结合axios实现HTTP请求的拦截和错误处理,展示了如何定义控制器和应用@Get装饰器到其中的方法,以优雅地管理接口调用并处理响应状态。
1. 安装依赖
首先,我们需要安装axios来处理HTTP请求。
1npm install axios -S
2. 定义控制器
接下来,我们定义一个简单的控制器类,后续将会在其中的方法上使用我们的装饰器。
1class Controller {
2 constructor() {
3
4 }
5 getList () {
6
7 }
8}
3. 定义装饰器
为了能够传递URL参数给装饰器,我们需要使用装饰器工厂。装饰器工厂就是一个返回装饰器函数的函数。
这个@Get装饰器会拦截被装饰的方法,使用axios发送一个GET请求,并将请求结果和状态码作为参数传递给原方法。
- 装饰器工厂:
Get(url: string)接收一个url字符串,并返回一个方法装饰器。 - 方法装饰器: 返回的函数接收三个参数:
target(类的原型),key(方法名),和descriptor(属性描述符)。 - descriptor.value: 我们通过
descriptor.value可以获取到原始的方法实现。我们保存它,然后在axios请求成功或失败后,调用原始方法并传入相应的数据。
1import axios from 'axios';
2
3const Get = (url: string): MethodDecorator => {
4 return (target, key, descriptor: PropertyDescriptor) => {
5 const fnc = descriptor.value; // 获取原始方法
6 axios.get(url).then(res => {
7 // 请求成功,调用原始方法并传入结果
8 fnc(res, {
9 status: 200,
10 })
11 }).catch(e => {
12 // 请求失败,调用原始方法并传入错误信息
13 fnc(e, {
14 status: 500,
15 })
16 })
17 }
18}
4. 完整代码示例
下面是结合了控制器和@Get装饰器的完整代码。getList方法被@Get装饰后,会自动发起网络请求,并将结果打印出来。
1import axios from 'axios';
2
3// Get 装饰器工厂
4const Get = (url: string): MethodDecorator => {
5 return (target, key, descriptor: PropertyDescriptor) => {
6 const fnc = descriptor.value;
7 axios.get(url).then(res => {
8 fnc(res, {
9 status: 200,
10 })
11 }).catch(e => {
12 fnc(e, {
13 status: 500,
14 })
15 })
16 }
17}
18
19// 定义控制器
20class Controller {
21 constructor() {
22
23 }
24
25 @Get('https://api.apiopen.top/api/getHaoKanVideo?page=0&size=10')
26 getList (res: any, status: any) {
27 if (status.status === 200) {
28 console.log(res.data.result.list, status);
29 } else {
30 console.error('Request Failed:', res);
31 }
32 }
33}
34
35// 实例化控制器以触发装饰器逻辑
36new Controller();