引用云对象
| 名称 | 类型 | 必填 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| objectName | string (string.CloudObjectString) | 是 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| options | UniCloudImportObjectOptions | 否 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| 类型 | ||||||
|---|---|---|---|---|---|---|
| UniCloudCloudObjectCaller | ||||||
|
callMethod
| 名称 | 类型 | 必填 |
|---|---|---|
| methodName | string | 是 |
| args | Array<any> | 是 |
| 类型 |
|---|
| Promise<T> |
_getArgs
| 名称 | 类型 | 必填 |
|---|---|---|
| args | Array<any> | 否 |
| 类型 |
|---|
| Array<any> |
由于强类型语言的限制,uni-app-x在编译时需要读取本地云对象导出的方法列表生成客户端对象。
index.obj.js无法被正确解析,请在云对象目录创建index.obj.d.ts声明云对象内包含的方法。index.obj.d.ts示例代码如下:// index.obj.d.ts
type AnyFunction = (...args: any[]) => any;
declare const add: AnyFunction
declare const update: AnyFunction
declare const deleteRecord: AnyFunction
export { // 上面的写法可以自己调整,仅需保证export内包含所有方法即可
add,
update
deleteRecord as remove
}
4.13版本起支持,仅安卓端会构造对应的泛型的实例,web端和iOS端泛型仅作为类型使用。
用法:obj.add<泛型类型>()
在不传泛型时云对象方法返回的类型为Promise<any>,传入泛型后callFunction返回的类型为Promise<泛型类型>
代码示例
// 云对象todo代码
'use strict';
module.exports = {
async add(title, content) {
return {
errCode: 0,
errMsg: '',
detail: `Todo added, title: ${title}, content: ${content}`
}
},
}
// 客户端代码
const todo = uniCloud.importObject('todo')
type CallObjectResult = {
errCode : number
errMsg : string
detail : string
}
todo.add<CallObjectResult>('todo title', 'todo content').then((res) => {
const detail = res.detail // res类型为CallObjectResult,可直接通过.detail访问其中detail属性
console.log(detail)
}).catch((err : any | null) => {
console.error(err)
})