示例仅供参考,请以真机为主

Service 请求服务

服务层负责处理发起的请求, 并返回对服务端的响应。

配置

/config/dev.ts 开发模式:

import { proxy } from "./proxy";

export default {
	// 根地址
	host: proxy["/dev/"].target,

	// 请求地址
	get baseUrl() {
		// #ifdef H5
		return "/dev";
		// #endif

		// #ifndef H5
		return this.host + "";
		// #endif
	}
};

/config/prod.ts 生产模式:

import { proxy } from "./proxy";

export default {
	// 根地址
	host: proxy["/prod/"].target,

	// 请求地址
	get baseUrl() {
		// #ifdef H5
		return "/api";
		// #endif

		// #ifndef H5
		return this.host + "/api";
		// #endif
	}
};

编辑

  • 程序默认使用 eps 方式(即后端所有开放给 app 端的接口,都会在前端生成对应的方法),无需自己手动一个个添加:
// config/index.ts
{
	test: {
		// 是否开启
		eps: true;
	}
}
  • 当然也可以自己额外配置 service,在 service 目录下新建 test.ts 文件:
// service/test.ts
import { BaseService, Service } from "/@/cool";

@Service("test")
class Test extends BaseService {}

export default Test;

上面两种方式最终会合并生成 service 及描述文件

使用

引入

// 方式1
import { useCool } from "/@/cool";
const { service } = useCool();

// 方式2
import { service } from "/@/cool";

调用

// 通过方法
service.test.page().then((res) => {
	console.log(res);
});

// 请求其他
service
	.request({
		url: "http://xxxx",
		method: "GET",
		data: {},
		params: {}
	})
	.then((res) => {
		console.log(res);
	});

service 的结构是根据 接口路径 转化成对应的层级,打印出 service 瞅瞅。

Last Updated: