diff --git a/zh-cn/application-dev/database/data-persistence-by-preferences.md b/zh-cn/application-dev/database/data-persistence-by-preferences.md index c5a6f64a0c47e540aa14b3ca85f04d106db1ef7e..92404f30ca3d461456a516394946455d48f870e8 100644 --- a/zh-cn/application-dev/database/data-persistence-by-preferences.md +++ b/zh-cn/application-dev/database/data-persistence-by-preferences.md @@ -47,7 +47,7 @@ 1. 导入`@ohos.data.preferences`模块。 - ```js + ```ts import dataPreferences from '@ohos.data.preferences'; ``` @@ -56,7 +56,7 @@ Stage模型示例: - ```js + ```ts import UIAbility from '@ohos.app.ability.UIAbility'; import { BusinessError } from '@ohos.base'; import window from '@ohos.window'; @@ -73,7 +73,9 @@ // 请确保获取到Preferences实例后,再进行相关数据操作 }) } catch (err) { - console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`Failed to get preferences. Code:${code},message:${message}`); } } } @@ -82,7 +84,7 @@ FA模型示例: - ```js + ```ts import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base'; @@ -99,7 +101,9 @@ // 请确保获取到Preferences实例后,再进行相关数据操作 }) } catch (err) { - console.error(`Failed to get preferences. Code is ${err.code},message:${err.message}`); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`Failed to get preferences. Code is ${code},message:${message}`); } ``` @@ -114,7 +118,7 @@ 示例代码如下所示: - ```js + ```ts try { if (preferences.hasSync('startup')) { console.info("The key 'startup' is contained."); @@ -124,7 +128,9 @@ preferences.putSync('startup', 'auto'); } } catch (err) { - console.error(`Failed to check the key 'startup'. Code:${err.code}, message:${err.message}`); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`Failed to check the key 'startup'. Code:${code}, message:${message}`); } ``` @@ -132,12 +138,14 @@ 使用getSync()方法获取数据,即指定键对应的值。如果值为null或者非默认值类型,则返回默认数据。示例代码如下所示: - ```js + ```ts try { let val = preferences.getSync('startup', 'default'); console.info(`Succeeded in getting value of 'startup'. val: ${val}.`); } catch (err) { - console.error(`Failed to get value of 'startup'. Code:${err.code}, message:${err.message}`); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`Failed to get value of 'startup'. Code:${code}, message:${message}`); } ``` @@ -146,11 +154,13 @@ 使用deleteSync()方法删除指定键值对,示例代码如下所示: - ```js + ```ts try { preferences.deleteSync('startup'); } catch (err) { - console.error(`Failed to delete the key 'startup'. Code:${err.code}, message:${err.message}`); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`Failed to delete the key 'startup'. Code:${code}, message:${message}`); } ``` @@ -158,7 +168,7 @@ 应用存入数据到Preferences实例后,可以使用flush()方法实现数据持久化。示例代码如下所示: - ```js + ```ts try { preferences.flush((err: BusinessError) => { if (err) { @@ -168,7 +178,9 @@ console.info('Succeeded in flushing.'); }) } catch (err) { - console.error(`Failed to flush. Code:${err.code}, message:${err.message}`); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`Failed to flush. Code:${code}, message:${message}`); } ``` @@ -176,7 +188,7 @@ 应用订阅数据变更需要指定observer作为回调方法。订阅的Key值发生变更后,当执行flush()方法时,observer被触发回调。示例代码如下所示: - ```js + ```ts interface observer { key: string } @@ -213,7 +225,7 @@ 示例代码如下所示: - ```js + ```ts try { dataPreferences.deletePreferences(this.context, 'myStore', (err: BusinessError) => { if (err) { @@ -223,7 +235,9 @@ console.info('Succeeded in deleting preferences.'); }) } catch (err) { - console.error(`Failed to delete preferences. Code:${err.code}, message:${err.message}`); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`Failed to delete preferences. Code:${code}, message:${message}`); } ``` diff --git a/zh-cn/application-dev/database/data-sync-of-distributed-data-object.md b/zh-cn/application-dev/database/data-sync-of-distributed-data-object.md index 8f3cca0be0fac2dc1ec8bb1e1d7738309c914d68..cc81d2ab8e00d0d6061bd2ebc9b531440aba907e 100644 --- a/zh-cn/application-dev/database/data-sync-of-distributed-data-object.md +++ b/zh-cn/application-dev/database/data-sync-of-distributed-data-object.md @@ -115,6 +115,7 @@ ## 接口说明 以下是分布式对象跨设备数据同步功能的相关接口,大部分为异步接口。异步接口均有callback和Promise两种返回形式,下表均以callback形式为例,更多接口及使用方式请见[分布式数据对象](../reference/apis/js-apis-data-distributedobject.md)。 +本模块接口仅支持在JS文件中使用。 | 接口名称 | 描述 | | -------- | -------- | @@ -151,26 +152,17 @@ // 导入模块 import distributedDataObject from '@ohos.data.distributedDataObject'; import UIAbility from '@ohos.app.ability.UIAbility'; - import { BusinessError } from '@ohos.base'; - import window from '@ohos.window'; - - interface sourceObject{ - name: string, - age: number, - isVis: boolean - parent: { [key: string]: string }, - list: { [key: string]: string }[] - } + class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage: window.WindowStage) { - let source: sourceObject = { + onWindowStageCreate(windowStage) { + // 创建对象,该对象包含4个属性类型:string、number、boolean和Object + let localObject = distributedDataObject.create(this.context, { name: 'jack', age: 18, isVis: false, parent: { mother: 'jack mom', father: 'jack Dad' }, list: [{ mother: 'jack mom' }, { father: 'jack Dad' }] - } - let localObject: distributedDataObject.DataObject = distributedDataObject.create(this.context, source); + }); } } ``` @@ -184,43 +176,34 @@ import featureAbility from '@ohos.ability.featureAbility'; // 获取context let context = featureAbility.getContext(); - interface sourceObject{ - name: string, - age: number, - isVis: boolean - parent: { [key: string]: string }, - list: { [key: string]: string }[] - } - let source: sourceObject = { + // 创建对象,该对象包含4个属性类型:string、number、boolean和Object + let localObject = distributedDataObject.create(context, { name: 'jack', age: 18, isVis: false, parent: { mother: 'jack mom', father: 'jack Dad' }, list: [{ mother: 'jack mom' }, { father: 'jack Dad' }] - } - // 创建对象,该对象包含4个属性类型:string、number、boolean和Object - let localObject: distributedDataObject.DataObject = distributedDataObject.create(context, source); + }); ``` 4. 加入同步组网。同步组网中的数据对象分为发起方和被拉起方。 ```js // 设备1加入sessionId - let sessionId: string = '123456'; + let sessionId = '123456'; localObject.setSessionId(sessionId); // 和设备1协同的设备2加入同一个session // 创建对象,该对象包含4个属性类型:string、number、boolean和Object - let remoteSource: sourceObject = { + let remoteObject = distributedDataObject.create(this.context, { name: undefined, age: undefined, // undefined表示数据来自对端 isVis: true, parent: undefined, list: undefined - } - let remoteObject: distributedDataObject.DataObject = distributedDataObject.create(this.context, remoteSource); + }); // 收到status上线后remoteObject同步数据,即name变成jack,age是18 remoteObject.setSessionId(sessionId); ``` @@ -228,19 +211,18 @@ 5. 监听对象数据变更。可监听对端数据的变更,以callback作为变更回调实例。 ```js - interface ChangeCallback { - sessionId: string, - fields: Array - } + function changeCallback(sessionId, changeData) { + console.info(`change: ${sessionId}`); - localObject.on("change", (changeData:ChangeCallback) => { - console.info("change" + changeData.sessionId); - if (changeData.fields != null && changeData.fields != undefined) { - for (let index: number = 0; index < changeData.fields.length; index++) { - console.info(`The element ${localObject[changeData.fields[index]]} changed.`); - } + if (changeData !== null && changeData !== undefined) { + changeData.forEach(element => { + console.info(`The element ${localObject[element]} changed.`); + }); } - }); + } + + // 发起方要在changeCallback里刷新界面,则需要将正确的this绑定给changeCallback + localObject.on("change", this.changeCallback.bind(this)); ``` 6. 修改对象属性,对象属性支持基本类型(数字类型、布尔类型、字符串类型)以及复杂类型(数组、基本类型嵌套等)。 @@ -275,14 +257,7 @@ ```js // 删除变更回调changeCallback - localObject.off('change',(changeData: ChangeCallback) => { - console.info("change" + changeData.sessionId); - if (changeData.fields != null && changeData.fields != undefined) { - for (let index: number = 0; index < changeData.fields.length; index++) { - console.info("changed !" + changeData.fields[index] + " " + g_object[changeData.fields[index]]); - } - } - }); + localObject.off('change', this.changeCallback); // 删除所有的变更回调 localObject.off('change'); ``` @@ -290,32 +265,27 @@ 9. 监听分布式数据对象的上下线。可以监听对端分布式数据对象的上下线。 ```js - interface onStatusCallback { - sessionId: string, - networkId: string, - status: 'online' | 'offline' + function statusCallback(sessionId, networkId, status) { + // 业务处理 } - localObject.on('status', (statusCallback: onStatusCallback) => { - console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.networkId); - // 业务处理 - }); + localObject.on('status', this.statusCallback); ``` 10. 保存和撤回已保存的数据对象。 ```js // 保存数据对象,如果应用退出后组网内设备需要恢复对象数据时调用 - localObject.save("local").then((result: distributedDataObject.SaveSuccessResponse) => { + localObject.save('local').then((result) => { console.info(`Succeeded in saving. SessionId:${result.sessionId},version:${result.version},deviceId:${result.deviceId}`); - }).catch((err: BusinessError) => { + }).catch((err) => { console.error(`Failed to save. Code:${err.code},message:${err.message}`); }); // 撤回保存的数据对象 - localObject.revokeSave().then((result: distributedDataObject.RevokeSaveSuccessResponse) => { + localObject.revokeSave().then((result) => { console.info(`Succeeded in revokeSaving. Session:${result.sessionId}`); - }).catch((err: BusinessError) => { + }).catch((err) => { console.error(`Failed to revokeSave. Code:${err.code},message:${err.message}`); }); ``` @@ -323,16 +293,8 @@ 11. 删除监听分布式数据对象的上下线。可以指定删除监听的上下线回调;也可以不指定,这将会删除该分布式数据对象的所有上下线回调。 ```js - interface offStatusCallback { - sessionId: string, - deviceId: string, - status: 'online' | 'offline' - } // 删除上下线回调statusCallback - localObject.off('status', (statusCallback: offStatusCallback) => { - console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.deviceId); - // 业务处理 - }); + localObject.off('status', this.statusCallback); // 删除所有的上下线回调 localObject.off('status'); ``` @@ -341,7 +303,7 @@ ```js localObject.setSessionId(() => { - console.info('leave all session.'); + console.info('leave all session.'); }); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-distributedobject.md b/zh-cn/application-dev/reference/apis/js-apis-data-distributedobject.md index 4cc5b90e71aea7bb82123ba6b47ff0648ff2e756..74fed8386d69e59edf3f346a8df23b3893a9de6d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-distributedobject.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-distributedobject.md @@ -5,6 +5,7 @@ > **说明:** > > 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> 本模块接口仅支持在JS文件中使用。 ## 导入模块 @@ -42,20 +43,10 @@ FA模型示例: // 导入模块 import distributedObject from '@ohos.data.distributedDataObject'; import featureAbility from '@ohos.ability.featureAbility'; -import { BusinessError } from '@ohos.base'; // 获取context let context = featureAbility.getContext(); -interface sourceObject{ - name: string, - age: number, - isVis: boolean -} -let source: sourceObject = { - name: "amy", - age:18, - isVis:false -} -let g_object: distributedObject.DataObject = distributedObject.create(context, source); +// 创建对象,该对象包含4个属性类型:string、number、boolean和Object +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); ``` Stage模型示例: @@ -64,23 +55,13 @@ Stage模型示例: // 导入模块 import distributedObject from '@ohos.data.distributedDataObject'; import UIAbility from '@ohos.app.ability.UIAbility'; -import { BusinessError } from '@ohos.base'; -import window from '@ohos.window'; - -let g_object: distributedObject.DataObject = null; -interface sourceObject{ - name: string, - age: number, - isVis: boolean -} + +let g_object; + class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage: window.WindowStage) { - let source: sourceObject = { - name: "amy", - age:18, - isVis:false - } - g_object = distributedObject.create(this.context, source); + onWindowStageCreate(windowStage){ + // 创建对象,该对象包含4个属性类型:string、number、boolean和Object + g_object = distributedObject.create(this.context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); } } ``` @@ -103,7 +84,7 @@ genSessionId(): string ```js import distributedObject from '@ohos.data.distributedDataObject'; -let sessionId: string = distributedObject.genSessionId(); +let sessionId = distributedObject.genSessionId(); ``` ## SaveSuccessResponse9+ @@ -239,13 +220,13 @@ setSessionId(sessionId?: string): Promise<void> // g_object加入分布式组网 g_object.setSessionId(distributedObject.genSessionId()).then (()=>{ console.info("join session."); - }).catch((error: BusinessError)=>{ + }).catch((error)=>{ console.info("error:" + error.code + error.message); }); // 退出分布式组网 g_object.setSessionId().then (()=>{ console.info("leave all session."); - }).catch((error: BusinessError)=>{ + }).catch((error)=>{ console.info("error:" + error.code + error.message); }); ``` @@ -268,18 +249,15 @@ on(type: 'change', callback: Callback<{ sessionId: string, fields: Array<stri **示例:** ```js -interface ChangeCallback { - sessionId: string, - fields: Array -} -g_object.on("change", (changeData: ChangeCallback) => { - console.info("change" + changeData.sessionId); - if (changeData.fields != null && changeData.fields != undefined) { - for (let index: number = 0; index < changeData.fields.length; index++) { - console.info("changed !" + changeData.fields[index] + " " + g_object[changeData.fields[index]]); - } +globalThis.changeCallback = (sessionId, changeData) => { + console.info("change" + sessionId); + if (changeData != null && changeData != undefined) { + changeData.forEach(element => { + console.info("changed !" + element + " " + g_object[element]); + }); } -}); +} +g_object.on("change", globalThis.changeCallback); ``` ### off('change')9+ @@ -302,14 +280,7 @@ off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array<st ```js // 删除数据变更回调changeCallback -g_object.off("change", (changeData:ChangeCallback) => { - console.info("change" + changeData.sessionId); - if (changeData.fields != null && changeData.fields != undefined) { - for (let index: number = 0; index < changeData.fields.length; index++) { - console.info("changed !" + changeData.fields[index] + " " + g_object[changeData.fields[index]]); - } - } -}); +g_object.off("change", globalThis.changeCallback); // 删除所有的数据变更回调 g_object.off("change"); ``` @@ -332,15 +303,10 @@ on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, st **示例:** ```js -interface onStatusCallback { - sessionId: string, - networkId: string, - status: 'online' | 'offline' +globalThis.statusCallback = (sessionId, networkId, status) => { + globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; } - -g_object.on("status", (statusCallback:onStatusCallback) => { - console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.networkId); -}); +g_object.on("status", globalThis.statusCallback); ``` ### off('status')9+ @@ -362,15 +328,11 @@ off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, s **示例:** ```js -interface offStatusCallback { - sessionId: string, - networkId: string, - status: 'online' | 'offline' +globalThis.statusCallback = (sessionId, networkId, status) => { + globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; } // 删除上下线回调changeCallback -g_object.off("status", (statusCallback:StatusCallback) => { - console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.networkId); -}); +g_object.off("status",globalThis.statusCallback); // 删除所有的上下线回调 g_object.off("status"); ``` @@ -402,7 +364,7 @@ save(deviceId: string, callback: AsyncCallback<SaveSuccessResponse>): void ```ts g_object.setSessionId("123456"); -g_object.save("local", (err: BusinessError, result:distributedObject.SaveSuccessResponse) => { +g_object.save("local", (err, result) => { if (err) { console.info("save failed, error code = " + err.code); console.info("save failed, error message: " + err.message); @@ -447,12 +409,12 @@ save(deviceId: string): Promise<SaveSuccessResponse> ```js g_object.setSessionId("123456"); -g_object.save("local").then((result: distributedObject.SaveSuccessResponse) => { +g_object.save("local").then((result) => { console.info("save callback"); console.info("save sessionId " + result.sessionId); console.info("save version " + result.version); console.info("save deviceId " + result.deviceId); -}).catch((err: BusinessError) => { +}).catch((err) => { console.info("save failed, error code = " + err.code); console.info("save failed, error message: " + err.message); }); @@ -480,7 +442,7 @@ revokeSave(callback: AsyncCallback<RevokeSaveSuccessResponse>): void ```js g_object.setSessionId("123456"); // 持久化数据 -g_object.save("local", (err: BusinessError, result: distributedObject.SaveSuccessResponse) => { +g_object.save("local", (err, result) => { if (err) { console.info("save failed, error code = " + err.code); console.info("save failed, error message: " + err.message); @@ -492,7 +454,7 @@ g_object.save("local", (err: BusinessError, result: distributedObject.SaveSucces console.info("save deviceId: " + result.deviceId); }); // 删除持久化保存的数据 -g_object.revokeSave((err: BusinessError, result: distributedObject.RevokeSaveSuccessResponse) => { +g_object.revokeSave((err, result) => { if (err) { console.info("revokeSave failed, error code = " + err.code); console.info("revokeSave failed, error message: " + err.message); @@ -525,20 +487,20 @@ revokeSave(): Promise<RevokeSaveSuccessResponse> ```ts g_object.setSessionId("123456"); // 持久化数据 -g_object.save("local").then((result: distributedObject.SaveSuccessResponse) => { +g_object.save("local").then((result) => { console.info("save callback"); console.info("save sessionId " + result.sessionId); console.info("save version " + result.version); console.info("save deviceId " + result.deviceId); -}).catch((err: BusinessError) => { +}).catch((err) => { console.info("save failed, error code = " + err.code); console.info("save failed, error message: " + err.message); }); // 删除持久化保存的数据 -g_object.revokeSave().then((result: distributedObject.RevokeSaveSuccessResponse) => { +g_object.revokeSave().then((result) => { console.info("revokeSave callback"); console.info("sessionId" + result.sessionId); -}).catch((err: BusinessError)=> { +}).catch((err)=> { console.info("revokeSave failed, error code = " + err.code); console.info("revokeSave failed, error message = " + err.message); }); @@ -573,17 +535,8 @@ createDistributedObject(source: object): DistributedObject ```js import distributedObject from '@ohos.data.distributedDataObject'; -interface sourceObject{ - name: string, - age: number, - isVis: boolean -} -let source: sourceObject = { - name: "amy", - age:18, - isVis:false -} -let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source); +// 创建对象,对象包含4个属性类型,string,number,boolean和Object +let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); ``` ## DistributedObject(deprecated) @@ -620,17 +573,7 @@ setSessionId(sessionId?: string): boolean ```js import distributedObject from '@ohos.data.distributedDataObject'; -interface sourceObject{ - name: string, - age: number, - isVis: boolean -} -let source: sourceObject = { - name: "amy", - age:18, - isVis:false -} -let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source); +let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});; // g_object加入分布式组网 g_object.setSessionId(distributedObject.genSessionId()); // 设置为""退出分布式组网 @@ -660,29 +603,16 @@ on(type: 'change', callback: Callback<{ sessionId: string, fields: Array<stri ```js import distributedObject from '@ohos.data.distributedDataObject'; -interface sourceObject{ - name: string, - age: number, - isVis: boolean -} -interface ChangeCallback { - sessionId: string, - fields: Array -} -let source: sourceObject = { - name: "amy", - age:18, - isVis:false -} -let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source); -g_object.on("change", (changeData:ChangeCallback) => { - console.info("change" + changeData.sessionId); - if (changeData.fields != null && changeData.fields != undefined) { - for (let index: number = 0; index < changeData.fields.length; index++) { - console.info("changed !" + changeData.fields[index] + " " + g_object[changeData.fields[index]]); - } +let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +globalThis.changeCallback = (sessionId, changeData) => { + console.info("change" + sessionId); + if (changeData != null && changeData != undefined) { + changeData.forEach(element => { + console.info("changed !" + element + " " + g_object[element]); + }); } -}); +} +g_object.on("change", globalThis.changeCallback); ``` ### off('change')(deprecated) @@ -709,30 +639,9 @@ off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array<st ```js import distributedObject from '@ohos.data.distributedDataObject'; -interface sourceObject{ - name: string, - age: number, - isVis: boolean -} -interface ChangeCallback { - sessionId: string, - fields: Array -} -let source: sourceObject = { - name: "amy", - age:18, - isVis:false -} -let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source); +let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); // 删除数据变更回调changeCallback -g_object.off("change", (changeData:ChangeCallback) => { - console.info("change" + changeData.sessionId); - if (changeData.fields != null && changeData.fields != undefined) { - for (let index: number = 0; index < changeData.fields.length; index++) { - console.info("changed !" + changeData.fields[index] + " " + g_object[changeData.fields[index]]); - } - } -}); +g_object.off("change", globalThis.changeCallback); // 删除所有的数据变更回调 g_object.off("change"); ``` @@ -760,27 +669,11 @@ on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, st ```js import distributedObject from '@ohos.data.distributedDataObject'; - -interface sourceObject{ - name: string, - age: number, - isVis: boolean -} -interface StatusCallback { - sessionId: string, - networkId: string, - status: 'online' | 'offline' -} -let source: sourceObject = { - name: "amy", - age:18, - isVis:false +globalThis.statusCallback = (sessionId, networkId, status) => { + globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; } -let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source); - -g_object.on("status", (statusCallback:StatusCallback) => { - console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.networkId); -}); +let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +g_object.on("status", globalThis.statusCallback); ``` ### off('status')(deprecated) @@ -807,26 +700,12 @@ off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, s ```js import distributedObject from '@ohos.data.distributedDataObject'; -interface sourceObject{ - name: string, - age: number, - isVis: boolean +let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +globalThis.statusCallback = (sessionId, networkId, status) => { + globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; } -interface offStatusCallback { - sessionId: string, - deviceId: string, - status: 'online' | 'offline' -} -let source: sourceObject = { - name: "amy", - age:18, - isVis:false -} -let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source); // 删除上下线回调changeCallback -g_object.off("status", (statusCallback:offStatusCallback) => { - console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.deviceId); -}); +g_object.off("status",globalThis.statusCallback); // 删除所有的上下线回调 g_object.off("status"); -``` +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-preferences.md b/zh-cn/application-dev/reference/apis/js-apis-data-preferences.md index b9ea1bd0f99eafe3ea98bd3d49f2d7dee68422e6..45793b14f441c7b11870acfdbbbaf84f596b9388 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-preferences.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-preferences.md @@ -12,7 +12,7 @@ ## 导入模块 -```js +```ts import data_preferences from '@ohos.data.preferences'; ``` @@ -46,13 +46,13 @@ getPreferences(context: Context, name: string, callback: AsyncCallback<Prefer FA模型示例: -```js +```ts // 获取context import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base'; let context = featureAbility.getContext(); -let preferences: data_preferences.Preferences = null; +let preferences: data_preferences.Preferences | null = null; try { data_preferences.getPreferences(context, 'myStore', (err: BusinessError, val: data_preferences.Preferences) => { @@ -64,7 +64,9 @@ try { console.info("Succeeded in getting preferences."); }) } catch (err) { - console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get preferences. code =" + code + ", message =" + message); } ``` @@ -75,7 +77,7 @@ import UIAbility from '@ohos.app.ability.UIAbility'; import { BusinessError } from '@ohos.base'; import window from '@ohos.window'; -let preferences: data_preferences.Preferences = null; +let preferences: data_preferences.Preferences | null = null; class EntryAbility extends UIAbility { onWindowStageCreate(windowStage: window.WindowStage) { @@ -89,7 +91,9 @@ class EntryAbility extends UIAbility { console.info("Succeeded in getting preferences."); }) } catch (err) { - console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get preferences. code =" + code + ", message =" + message); } } } @@ -120,14 +124,14 @@ getPreferences(context: Context, name: string): Promise<Preferences> FA模型示例: -```js +```ts // 获取context import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base' let context = featureAbility.getContext(); -let preferences: data_preferences.Preferences = null; +let preferences: data_preferences.Preferences | null = null; try { let promise = data_preferences.getPreferences(context, 'myStore'); promise.then((object: data_preferences.Preferences) => { @@ -136,8 +140,10 @@ try { }).catch((err: BusinessError) => { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); }) -} catch(err) { - console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get preferences. code =" + code + ", message =" + message); } ``` @@ -148,7 +154,7 @@ import UIAbility from '@ohos.app.ability.UIAbility'; import { BusinessError } from '@ohos.base' import window from '@ohos.window'; -let preferences: data_preferences.Preferences = null; +let preferences: data_preferences.Preferences | null = null; class EntryAbility extends UIAbility { onWindowStageCreate(windowStage: window.WindowStage) { @@ -160,8 +166,10 @@ class EntryAbility extends UIAbility { }).catch((err: BusinessError) => { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); }) - } catch(err) { - console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get preferences. code =" + code + ", message =" + message); } } } @@ -196,13 +204,13 @@ getPreferences(context: Context, options: Options, callback: AsyncCallback<Pr FA模型示例: -```js +```ts // 获取context import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base' let context = featureAbility.getContext(); -let preferences: data_preferences.Preferences = null; +let preferences: data_preferences.Preferences | null = null; try { let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; @@ -215,7 +223,9 @@ try { console.info("Succeeded in getting preferences."); }) } catch (err) { - console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get preferences. code =" + code + ", message =" + message); } ``` @@ -227,7 +237,7 @@ import UIAbility from '@ohos.app.ability.UIAbility'; import { BusinessError } from '@ohos.base' import window from '@ohos.window'; -let preferences: data_preferences.Preferences = null; +let preferences: data_preferences.Preferences | null = null; class EntryAbility extends UIAbility { onWindowStageCreate(windowStage: window.WindowStage) { @@ -242,7 +252,9 @@ class EntryAbility extends UIAbility { console.info("Succeeded in getting preferences."); }) } catch (err) { - console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get preferences. code =" + code + ", message =" + message); } } } @@ -282,13 +294,13 @@ getPreferences(context: Context, options: Options): Promise<Preferences> FA模型示例: -```js +```ts // 获取context import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base' let context = featureAbility.getContext(); -let preferences: data_preferences.Preferences = null; +let preferences: data_preferences.Preferences | null = null; try { let options: data_preferences.Options = { name: 'myStore' }; let promise = data_preferences.getPreferences(context, options); @@ -298,8 +310,10 @@ try { }).catch((err: BusinessError) => { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); }) -} catch(err) { - console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get preferences. code =" + code + ", message =" + message); } ``` @@ -310,7 +324,7 @@ import UIAbility from '@ohos.app.ability.UIAbility'; import { BusinessError } from '@ohos.base' import window from '@ohos.window'; -let preferences: data_preferences.Preferences = null; +let preferences: data_preferences.Preferences | null = null; class EntryAbility extends UIAbility { onWindowStageCreate(windowStage: window.WindowStage) { @@ -323,8 +337,10 @@ class EntryAbility extends UIAbility { }).catch((err: BusinessError) => { console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); }) - } catch(err) { - console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get preferences. code =" + code + ", message =" + message); } } } @@ -364,19 +380,21 @@ getPreferencesSync(context: Context, options: Options): Preferences FA模型示例: -```js +```ts // 获取context import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base' let context = featureAbility.getContext(); -let preferences: data_preferences.Preferences = null; +let preferences: data_preferences.Preferences | null = null; try { let options: data_preferences.Options = { name: 'myStore' }; preferences = data_preferences.getPreferencesSync(context, options); -} catch(err) { - console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get preferences. code =" + code + ", message =" + message); } ``` @@ -387,15 +405,17 @@ import UIAbility from '@ohos.app.ability.UIAbility'; import { BusinessError } from '@ohos.base' import window from '@ohos.window'; -let preferences: data_preferences.Preferences = null; +let preferences: data_preferences.Preferences | null = null; class EntryAbility extends UIAbility { onWindowStageCreate(windowStage: window.WindowStage) { try { let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; preferences = data_preferences.getPreferencesSync(this.context, options); - } catch(err) { - console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get preferences. code =" + code + ", message =" + message); } } } @@ -431,7 +451,7 @@ deletePreferences(context: Context, name: string, callback: AsyncCallback<voi FA模型示例: -```js +```ts // 获取context import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base' @@ -447,7 +467,9 @@ try { console.info("Succeeded in deleting preferences." ); }) } catch (err) { - console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to delete preferences. code =" + code + ", message =" + message); } ``` @@ -469,7 +491,9 @@ class EntryAbility extends UIAbility { console.info("Succeeded in deleting preferences." ); }) } catch (err) { - console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to delete preferences. code =" + code + ", message =" + message); } } } @@ -510,7 +534,7 @@ deletePreferences(context: Context, name: string): Promise<void> FA模型示例: -```js +```ts // 获取context import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base' @@ -524,8 +548,10 @@ try { }).catch((err: BusinessError) => { console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); }) -} catch(err) { - console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to delete preferences. code =" + code + ", message =" + message); } ``` @@ -545,8 +571,10 @@ class EntryAbility extends UIAbility { }).catch((err: BusinessError) => { console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); }) - } catch(err) { - console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to delete preferences. code =" + code + ", message =" + message); } } } @@ -584,7 +612,7 @@ deletePreferences(context: Context, options: Options, callback: AsyncCallback< FA模型示例: -```js +```ts // 获取context import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base' @@ -601,7 +629,9 @@ try { console.info("Succeeded in deleting preferences." ); }) } catch (err) { - console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to delete preferences. code =" + code + ", message =" + message); } ``` @@ -624,7 +654,9 @@ class EntryAbility extends UIAbility { console.info("Succeeded in deleting preferences." ); }) } catch (err) { - console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to delete preferences. code =" + code + ", message =" + message); } } } @@ -668,7 +700,7 @@ deletePreferences(context: Context, options: Options): Promise<void> FA模型示例: -```js +```ts // 获取context import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base' @@ -683,8 +715,10 @@ try { }).catch((err: BusinessError) => { console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); }) -} catch(err) { - console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to delete preferences. code =" + code + ", message =" + message); } ``` @@ -705,8 +739,10 @@ class EntryAbility extends UIAbility { }).catch((err: BusinessError) => { console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); }) - } catch(err) { - console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to delete preferences. code =" + code + ", message =" + message); } } } @@ -737,7 +773,7 @@ removePreferencesFromCache(context: Context, name: string, callback: AsyncCallba FA模型示例: -```js +```ts // 获取context import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base' @@ -752,7 +788,9 @@ try { console.info("Succeeded in removing preferences."); }) } catch (err) { - console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to remove preferences. code =" + code + ", message =" + message); } ``` @@ -774,7 +812,9 @@ class EntryAbility extends UIAbility { console.info("Succeeded in removing preferences."); }) } catch (err) { - console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to remove preferences. code =" + code + ", message =" + message); } } } @@ -809,7 +849,7 @@ removePreferencesFromCache(context: Context, name: string): Promise<void> FA模型示例: -```js +```ts // 获取context import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base' @@ -822,8 +862,10 @@ try { }).catch((err: BusinessError) => { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); }) -} catch(err) { - console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to remove preferences. code =" + code + ", message =" + message); } ``` @@ -843,8 +885,10 @@ class EntryAbility extends UIAbility { }).catch((err: BusinessError) => { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); }) - } catch(err) { - console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to remove preferences. code =" + code + ", message =" + message); } } } @@ -873,14 +917,16 @@ removePreferencesFromCacheSync(context: Context, name: string): void FA模型示例: -```js +```ts // 获取context import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); try { data_preferences.removePreferencesFromCacheSync(context, 'myStore'); -} catch(err) { - console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to remove preferences. code =" + code + ", message =" + message); } ``` @@ -893,8 +939,10 @@ class EntryAbility extends UIAbility { onWindowStageCreate(windowStage: window.WindowStage) { try { data_preferences.removePreferencesFromCacheSync(this.context, 'myStore'); - } catch(err) { - console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to remove preferences. code =" + code + ", message =" + message); } } } @@ -933,7 +981,7 @@ removePreferencesFromCache(context: Context, options: Options, callback: AsyncCa FA模型示例: -```js +```ts // 获取context import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base' @@ -948,7 +996,9 @@ try { console.info("Succeeded in removing preferences."); }) } catch (err) { - console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to remove preferences. code =" + code + ", message =" + message); } ``` @@ -971,7 +1021,9 @@ class EntryAbility extends UIAbility { console.info("Succeeded in removing preferences."); }) } catch (err) { - console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to remove preferences. code =" + code + ", message =" + message); } } } @@ -1015,7 +1067,7 @@ removePreferencesFromCache(context: Context, options: Options): Promise<void& FA模型示例: -```js +```ts // 获取context import featureAbility from '@ohos.ability.featureAbility'; import { BusinessError } from '@ohos.base' @@ -1028,8 +1080,10 @@ try { }).catch((err: BusinessError) => { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); }) -} catch(err) { - console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to remove preferences. code =" + code + ", message =" + message); } ``` @@ -1050,8 +1104,10 @@ class EntryAbility extends UIAbility { }).catch((err: BusinessError) => { console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); }) - } catch(err) { - console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to remove preferences. code =" + code + ", message =" + message); } } } @@ -1089,15 +1145,17 @@ removePreferencesFromCacheSync(context: Context, options: Options):void FA模型示例: -```js +```ts // 获取context import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); try { let options: data_preferences.Options = { name: 'myStore' }; data_preferences.removePreferencesFromCacheSync(context, options); -} catch(err) { - console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to remove preferences. code =" + code + ", message =" + message); } ``` @@ -1112,8 +1170,10 @@ class EntryAbility extends UIAbility { try { let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; data_preferences.removePreferencesFromCacheSync(this.context, options); - } catch(err) { - console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to remove preferences. code =" + code + ", message =" + message); } } } @@ -1155,7 +1215,7 @@ get(key: string, defValue: ValueType, callback: AsyncCallback<ValueType>): **示例:** -```js +```ts try { preferences.get('startup', 'default', (err: BusinessError, val: data_preferences.ValueType) => { if (err) { @@ -1165,7 +1225,9 @@ try { console.info("Succeeded in getting value of 'startup'. val: " + val); }) } catch (err) { - console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get value of 'startup'. code =" + code + ", message =" + message); } ``` @@ -1193,7 +1255,7 @@ get(key: string, defValue: ValueType): Promise<ValueType> **示例:** -```js +```ts try { let promise = preferences.get('startup', 'default'); promise.then((data: data_preferences.ValueType) => { @@ -1201,8 +1263,10 @@ try { }).catch((err: BusinessError) => { console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); }) -} catch(err) { - console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get value of 'startup'. code =" + code + ", message =" + message); } ``` @@ -1229,12 +1293,14 @@ getSync(key: string, defValue: ValueType): ValueType **示例:** -```js +```ts try { let value: data_preferences.ValueType = preferences.getSync('startup', 'default'); console.info("Succeeded in getting value of 'startup'. Data: " + value); -} catch(err) { - console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get value of 'startup'. code =" + code + ", message =" + message); } ``` @@ -1254,19 +1320,28 @@ getAll(callback: AsyncCallback<Object>): void; **示例:** -```js +```ts +// 由于ArkTS中无Object.keys,且无法使用for..in... +// 若报ArkTS问题,请将此方法单独抽离至一个ts文件中并暴露,在需要用到的ets文件中引入使用 +function getObjKeys(obj: Object): string[] { + let keys = Object.keys(obj); + return keys; +} + try { - preferences.getAll((err: BusinessError, value: data_preferences.ValueType) => { + preferences.getAll((err: BusinessError, value: Object) => { if (err) { console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); return; } - let allKeys = Object.keys(value); + let allKeys = getObjKeys(value); console.info("getAll keys = " + allKeys); console.info("getAll object = " + JSON.stringify(value)); }) } catch (err) { - console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get all key-values. code =" + code + ", message =" + message); } ``` @@ -1287,18 +1362,27 @@ getAll(): Promise<Object> **示例:** -```js +```ts +// 由于ArkTS中无Object.keys,且无法使用for..in... +// 若报ArkTS问题,请将此方法单独抽离至一个ts文件中并暴露,在需要用到的ets文件中引入使用 +function getObjKeys(obj: Object): string[] { + let keys = Object.keys(obj); + return keys; +} + try { let promise = preferences.getAll(); - promise.then((value: data_preferences.ValueType) => { - let allKeys = Object.keys(value); + promise.then((value: Object) => { + let allKeys = getObjKeys(value); console.info('getAll keys = ' + allKeys); console.info("getAll object = " + JSON.stringify(value)); }).catch((err: BusinessError) => { console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); }) } catch (err) { - console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get all key-values. code =" + code + ", message =" + message); } ``` @@ -1318,14 +1402,23 @@ getAllSync(): Object **示例:** -```js +```ts +// 由于ArkTS中无Object.keys,且无法使用for..in... +// 若报ArkTS问题,请将此方法单独抽离至一个ts文件中并暴露,在需要用到的ets文件中引入使用 +function getObjKeys(obj: Object): string[] { + let keys = Object.keys(obj); + return keys; +} + try { let value = preferences.getAllSync(); - let allKeys = Object.keys(value); + let allKeys = getObjKeys(value); console.info('getAll keys = ' + allKeys); console.info("getAll object = " + JSON.stringify(value)); } catch (err) { - console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get all key-values. code =" + code + ", message =" + message); } ``` @@ -1347,7 +1440,7 @@ put(key: string, value: ValueType, callback: AsyncCallback<void>): void **示例:** -```js +```ts try { preferences.put('startup', 'auto', (err: BusinessError) => { if (err) { @@ -1357,7 +1450,9 @@ try { console.info("Succeeded in putting value of 'startup'."); }) } catch (err) { - console.error("Failed to put value of 'startup'. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to put value of 'startup'. code =" + code + ", message =" + message); } ``` @@ -1385,7 +1480,7 @@ put(key: string, value: ValueType): Promise<void> **示例:** -```js +```ts try { let promise = preferences.put('startup', 'auto'); promise.then(() => { @@ -1393,8 +1488,10 @@ try { }).catch((err: BusinessError) => { console.error("Failed to put value of 'startup'. code =" + err.code +", message =" + err.message); }) -} catch(err) { - console.error("Failed to put value of 'startup'. code =" + err.code +", message =" + err.message); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to put value of 'startup'. code =" + code +", message =" + message); } ``` @@ -1416,11 +1513,13 @@ putSync(key: string, value: ValueType): void **示例:** -```js +```ts try { preferences.putSync('startup', 'auto'); -} catch(err) { - console.error("Failed to put value of 'startup'. code =" + err.code +", message =" + err.message); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to put value of 'startup'. code =" + code +", message =" + message); } ``` @@ -1442,7 +1541,7 @@ has(key: string, callback: AsyncCallback<boolean>): void **示例:** -```js +```ts try { preferences.has('startup', (err: BusinessError, val: boolean) => { if (err) { @@ -1456,7 +1555,9 @@ try { } }) } catch (err) { - console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to check the key 'startup'. code =" + code + ", message =" + message); } ``` @@ -1483,7 +1584,7 @@ has(key: string): Promise<boolean> **示例:** -```js +```ts try { let promise = preferences.has('startup'); promise.then((val: boolean) => { @@ -1495,8 +1596,10 @@ try { }).catch((err: BusinessError) => { console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); }) -} catch(err) { - console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to check the key 'startup'. code =" + code + ", message =" + message); } ``` @@ -1523,7 +1626,7 @@ hasSync(key: string): boolean **示例:** -```js +```ts try { let isExist: boolean = preferences.hasSync('startup'); if (isExist) { @@ -1531,8 +1634,10 @@ try { } else { console.info("The key 'startup' dose not contain."); } -} catch(err) { - console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to check the key 'startup'. code =" + code + ", message =" + message); } ``` @@ -1554,7 +1659,7 @@ delete(key: string, callback: AsyncCallback<void>): void **示例:** -```js +```ts try { preferences.delete('startup', (err: BusinessError) => { if (err) { @@ -1564,7 +1669,9 @@ try { console.info("Succeeded in deleting the key 'startup'."); }) } catch (err) { - console.error("Failed to delete the key 'startup'. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to delete the key 'startup'. code =" + code + ", message =" + message); } ``` @@ -1591,7 +1698,7 @@ delete(key: string): Promise<void> **示例:** -```js +```ts try { let promise = preferences.delete('startup'); promise.then(() => { @@ -1599,8 +1706,10 @@ try { }).catch((err: BusinessError) => { console.error("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message); }) -} catch(err) { - console.error("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to delete the key 'startup'. code =" + code +", message =" + message); } ``` @@ -1621,11 +1730,13 @@ deleteSync(key: string): void **示例:** -```js +```ts try { preferences.deleteSync('startup'); -} catch(err) { - console.error("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to delete the key 'startup'. code =" + code +", message =" + message); } ``` @@ -1646,7 +1757,7 @@ flush(callback: AsyncCallback<void>): void **示例:** -```js +```ts try { preferences.flush((err: BusinessError) => { if (err) { @@ -1656,7 +1767,9 @@ try { console.info("Succeeded in flushing."); }) } catch (err) { - console.error("Failed to flush. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to flush. code =" + code + ", message =" + message); } ``` @@ -1677,7 +1790,7 @@ flush(): Promise<void> **示例:** -```js +```ts try { let promise = preferences.flush(); promise.then(() => { @@ -1686,7 +1799,9 @@ try { console.error("Failed to flush. code =" + err.code + ", message =" + err.message); }) } catch (err) { - console.error("Failed to flush. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to flush. code =" + code + ", message =" + message); } ``` @@ -1707,7 +1822,7 @@ clear(callback: AsyncCallback<void>): void **示例:** -```js +```ts try { preferences.clear((err: BusinessError) =>{ if (err) { @@ -1717,7 +1832,9 @@ try { console.info("Succeeded in clearing."); }) } catch (err) { - console.error("Failed to clear. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to clear. code =" + code + ", message =" + message); } ``` @@ -1738,7 +1855,7 @@ clear(): Promise<void> **示例:** -```js +```ts try { let promise = preferences.clear(); promise.then(() => { @@ -1746,8 +1863,10 @@ try { }).catch((err: BusinessError) => { console.error("Failed to clear. code =" + err.code + ", message =" + err.message); }) -} catch(err) { - console.error("Failed to clear. code =" + err.code + ", message =" + err.message); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to clear. code =" + code + ", message =" + message); } ``` @@ -1762,11 +1881,13 @@ clearSync(): void **示例:** -```js +```ts try { preferences.clearSync(); -} catch(err) { - console.error("Failed to clear. code =" + err.code + ", message =" + err.message); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to clear. code =" + code + ", message =" + message); } ``` @@ -1788,7 +1909,7 @@ on(type: 'change', callback: Callback<{ key : string }>): void **示例:** -```js +```ts interface observer { key: string } @@ -1818,7 +1939,9 @@ try { }) }) } catch (err) { - console.error("Failed to flush. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to flush. code =" + code + ", message =" + message); } ``` @@ -1849,7 +1972,7 @@ on(type: 'multiProcessChange', callback: Callback<{ key : string }>): void **示例1:** -```js +```ts interface observer { key: string } @@ -1879,13 +2002,15 @@ try { }) }) } catch (err) { - console.error("Failed to flush. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to flush. code =" + code + ", message =" + message); } ``` **示例2:** -```js +```ts interface observer { key: string } @@ -1909,7 +2034,9 @@ try { console.info("Succeeded in removing preferences."); }) } catch (err) { - console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to remove preferences. code =" + code + ", message =" + message); } try { @@ -1922,7 +2049,9 @@ try { console.info("Succeeded in getting preferences."); }) } catch (err) { - console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get preferences. code =" + code + ", message =" + message); } }); preferences.put('startup', 'manual', (err: BusinessError) => { @@ -1942,7 +2071,9 @@ try { }) }) } catch (err) { - console.error("Failed to flush. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to flush. code =" + code + ", message =" + message); } ``` @@ -1963,7 +2094,7 @@ off(type: 'change', callback?: Callback<{ key : string }>): void **示例:** -```js +```ts interface observer { key: string } @@ -1996,7 +2127,9 @@ try { }) }) } catch (err) { - console.error("Failed to flush. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to flush. code =" + code + ", message =" + message); } ``` @@ -2017,7 +2150,7 @@ off(type: 'multiProcessChange', callback?: Callback<{ key : string }>): vo **示例:** -```js +```ts interface observer { key: string } @@ -2051,7 +2184,9 @@ try { }) }) } catch (err) { - console.error("Failed to flush. code =" + err.code + ", message =" + err.message); + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to flush. code =" + code + ", message =" + message); } ``` ## ValueType