method实例
一个 method 实例对应一个请求信息描述,它拥有一次请求的 url、请求头、请求参数,以及响应数据处理、缓存数据处理等请求行为参数。通过 method 实例,你可以在任意的 js 环境下感受到统一的使用体验,只需要非常少的改动就可以正常运行起来,此外,method 实例将请求参数和请求行为参数放在了一起,更便于 api 的管理,而不是分散在多个代码文件中。
PromiseLike 特性
在[v2.16.0]之后,method 实例是一个 PromiseLike 实例,它拥有then/catch/finally函数,因此你可以按如下方式使用:
// 调用method的then函数
method.then(res => {
console.log(res);
});
// 捕获异常
method.catch(e => {
console.log(e);
});
// 请求完成调用
method.finally(() => {
console.log('请求完成');
});
此外,也可以通过await method来发送请求。
new Method()
自定义创建 method 实例。
- 类型
interface MethodConstructor {
new (
type: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD' | 'OPTIONS' | 'PATCH',
context: Alova,
url: string,
config?: AlovaMethodCreateConfig,
data?: Arg | string | FormData | Blob | ArrayBuffer | URLSearchParams | ReadableStream
): Method;
readonly prototype: Method;
}
- 参数
type:请求类型context:alova 实例url:请求 urlconfig:配置参数, 类型与alova.Get的 config 参数类型一致data:请求体数据
- 示例
import { Method } from 'alova';
import { alovaInstance } from './api';
const method = new Method('GET', alovaInstance, '/api/users', {
params: {
id: 1
}
});
getMethodKey()
获取 method 的 key 值,此 key 值作为 alova 内部缓存 key 使用。
- 类型
function getMethodKey(method: Method): string;
- 参数
method:method 实例
- 返回
传入的 method 实例的 key 值。
- 示例
import { getMethodKey } from 'alova';
const method = alova.Get('/api/users');
const methodKey = getMethodKey(method);
matchSnapshotMethod()
以method 匹配器的匹配方式获取已经请求过的 method 实例快照,并返回匹配的结果。
- 类型
type MethodFilter =
| string
| RegExp
| {
name?: string | RegExp;
filter?: MethodFilterHandler;
alova?: Alova;
};
function matchSnapshotMethod(
matcher: MethodFilter,
matchAll?: boolean
): Method[] | Method | undefined;
- 参数
matcher:method 匹配器matchAll:是否匹配全部,默认为 true
- 返回
matchAll 为 true 时返回 method 实例数组,否则返回 method 实例或 undefined
- 示例
import { matchSnapshotMethod } from 'alova';
await alova.Get('/api/users');
const snapshotMethod = matchSnapshotMethod({
name: 'user',
filter(method, i, methodArray) {
return method.url.includes('users');
},
alova: alova
});
method.headers
请求头。
- 类型
interface Method {
headers?: any;
}
method.baseURL
请求的基础路径,继承于alova 实例。
- 类型
interface Method {
baseURL: string;
}
method.url
创建 method 实例的 url。
- 类型
interface Method {
url: string;
}
method.type
请求类型。
- 类型:
interface Method {
type: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD' | 'OPTIONS' | 'PATCH';
}
method.data
请求 body。
- 类型
interface Method {
data?: any;
}
method.context
创建当前 method 的 alova 实例。
- 类型
interface Method {
context: Alova;
}
method.hitSource
打击源方法实例,当源方法实例请求成功时,当前方法实例的缓存将被失效。作为自动失效功能,只需设置打击源即可,而不需要手动调用invalidateCache失效缓存。此外,此功能在错综复杂的失效关系中比invalidateCache方法更简洁有效,该字段值可设置为 method 实例、其他 method 实例的 name、name 正则匹配,或者它们的数组。
- 类型
interface Method {
hitSource?: Method | string | RegExp | (Method | string | RegExp)[];
}