未验证 提交 eec9021f 编写于 作者: O openharmony_ci 提交者: Gitee

!23827 [翻译完成】#I7W54H

Merge pull request !23827 from Annie_wang/PR23106
...@@ -30,23 +30,23 @@ The preference persistent file of an application is stored in the application sa ...@@ -30,23 +30,23 @@ The preference persistent file of an application is stored in the application sa
The following table lists the APIs used for persisting user preference data. For more information about the APIs, see [User Preferences](../reference/apis/js-apis-data-preferences.md). The following table lists the APIs used for persisting user preference data. For more information about the APIs, see [User Preferences](../reference/apis/js-apis-data-preferences.md).
| API | Description | | API | Description |
|--------------------------------------------------------------------------------------------------|------------------------------------------------------------| | ------------------------------------------------------------ | ------------------------------------------------------------ |
| getPreferences(context: Context, name: string, callback: AsyncCallback<Preferences>): void | Obtain a **Preferences** instance. | | getPreferences(context: Context, name: string, callback: AsyncCallback<Preferences>): void | Obtains a **Preferences** instance. |
| putSync(key: string, value: ValueType): void | Writes data to the Preferences instance. You can use **flush()** to persist the **Preferences** instance data. An asynchronous API is also provided. | | putSync(key: string, value: ValueType): void | Writes data to the Preferences instance. You can use **flush()** to persist the **Preferences** instance data. An asynchronous API is also provided. |
| hasSync(key: string): void | Checks whether the **Preferences** instance contains a KV pair with the given key. The key cannot be empty. An asynchronous API is also provided. | | hasSync(key: string): void | Checks whether the **Preferences** instance contains a KV pair with the given key. The key cannot be empty. An asynchronous API is also provided. |
| getSync(key: string, defValue: ValueType): void | Obtains the value of the specified key. If the value is null or not of the default value type, **defValue** is returned. An asynchronous API is also provided. | | getSync(key: string, defValue: ValueType): void | Obtains the value of the specified key. If the value is null or not of the default value type, **defValue** is returned. An asynchronous API is also provided. |
| deleteSync(key: string): void | Deletes the KV pair with the given key from the **Preferences** instance. An asynchronous API is also provided. | | deleteSync(key: string): void | Deletes the KV pair with the given key from the **Preferences** instance. An asynchronous API is also provided. |
| flush(callback: AsyncCallback<void>): void | Flushes the data of this **Preferences** instance to a file for data persistence. | | flush(callback: AsyncCallback<void>): void | Flushes the data of this **Preferences** instance to a file for data persistence. |
| on(type: 'change', callback: Callback<{ key : string }>): void | Subscribes to data changes of the specified key. When the value of the specified key is changed and saved by **flush()**, a callback will be invoked to return the new data. | | on(type: 'change', callback: Callback<{ key : string }>): void | Subscribes to data changes of the specified key. When the value of the specified key is changed and saved by **flush()**, a callback will be invoked to return the new data. |
| off(type: 'change', callback?: Callback<{ key : string }>): void | Unsubscribes from data changes. | | off(type: 'change', callback?: Callback<{ key : string }>): void | Unsubscribes from data changes. |
| deletePreferences(context: Context, name: string, callback: AsyncCallback<void>): void | Deletes a **Preferences** instance from memory. If the **Preferences** instance has a persistent file, this API also deletes the persistent file.| | deletePreferences(context: Context, name: string, callback: AsyncCallback<void>): void | Deletes a **Preferences** instance from memory. If the **Preferences** instance has a persistent file, this API also deletes the persistent file. |
## How to Develop ## How to Develop
1. Import the **@ohos.data.preferences** module. 1. Import the **@ohos.data.preferences** module.
```js ```js
import dataPreferences from '@ohos.data.preferences'; import dataPreferences from '@ohos.data.preferences';
``` ```
...@@ -55,14 +55,16 @@ The following table lists the APIs used for persisting user preference data. For ...@@ -55,14 +55,16 @@ The following table lists the APIs used for persisting user preference data. For
Stage model: Stage model:
```js ```js
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base';
import window from '@ohos.window';
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage: window.WindowStage) {
try { try {
dataPreferences.getPreferences(this.context, 'mystore', (err, preferences) => { dataPreferences.getPreferences(this.context, 'myStore', (err: BusinessError, preferences: dataPreferences.Preferences) => {
if (err) { if (err) {
console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`); console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`);
return; return;
...@@ -79,15 +81,16 @@ The following table lists the APIs used for persisting user preference data. For ...@@ -79,15 +81,16 @@ The following table lists the APIs used for persisting user preference data. For
FA model: FA model:
```js ```js
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base';
// Obtain the context. // Obtain the context.
let context = featureAbility.getContext(); let context = featureAbility.getContext();
try { try {
dataPreferences.getPreferences(context, 'mystore', (err, preferences) => { dataPreferences.getPreferences(this.context, 'myStore', (err: BusinessError, preferences: dataPreferences.Preferences) => {
if (err) { if (err) {
console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`); console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`);
return; return;
...@@ -102,7 +105,7 @@ The following table lists the APIs used for persisting user preference data. For ...@@ -102,7 +105,7 @@ The following table lists the APIs used for persisting user preference data. For
3. Write data. 3. Write data.
Use **putSync()** to write data to the cached **Preferences** instance. After data is written, you can use **flush()** to persist the **Preferences** instance data to a file if necessary. Use **putSync()** to save data to the cached **Preferences** instance. After data is written, you can use **flush()** to persist the **Preferences** instance data to a file if necessary.
> **NOTE** > **NOTE**
> >
...@@ -110,7 +113,7 @@ The following table lists the APIs used for persisting user preference data. For ...@@ -110,7 +113,7 @@ The following table lists the APIs used for persisting user preference data. For
Example: Example:
```js ```js
try { try {
if (preferences.hasSync('startup')) { if (preferences.hasSync('startup')) {
...@@ -142,7 +145,7 @@ The following table lists the APIs used for persisting user preference data. For ...@@ -142,7 +145,7 @@ The following table lists the APIs used for persisting user preference data. For
Use **deleteSync()** to delete a KV pair.<br>Example: Use **deleteSync()** to delete a KV pair.<br>Example:
```js ```js
try { try {
preferences.deleteSync('startup'); preferences.deleteSync('startup');
...@@ -157,7 +160,7 @@ The following table lists the APIs used for persisting user preference data. For ...@@ -157,7 +160,7 @@ The following table lists the APIs used for persisting user preference data. For
```js ```js
try { try {
preferences.flush((err) => { preferences.flush((err: BusinessError) => {
if (err) { if (err) {
console.error(`Failed to flush. Code:${err.code}, message:${err.message}`); console.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
return; return;
...@@ -174,18 +177,20 @@ The following table lists the APIs used for persisting user preference data. For ...@@ -174,18 +177,20 @@ The following table lists the APIs used for persisting user preference data. For
Specify an observer as the callback to return the data changes for an application. When the value of the subscribed key is changed and saved by **flush()**, the observer callback will be invoked to return the new data. Example: Specify an observer as the callback to return the data changes for an application. When the value of the subscribed key is changed and saved by **flush()**, the observer callback will be invoked to return the new data. Example:
```js ```js
let observer = function (key) { interface observer {
console.info('The key' + key + 'changed.'); key: string
} }
preferences.on('change', observer); preferences.on('change', (key: observer) => {
console.info('The key' + key + 'changed.');
});
// The data is changed from 'auto' to 'manual'. // The data is changed from 'auto' to 'manual'.
preferences.put('startup', 'manual', (err) => { preferences.put('startup', 'manual', (err: BusinessError) => {
if (err) { if (err) {
console.error(`Failed to put the value of 'startup'. Code:${err.code},message:${err.message}`); console.error(`Failed to put the value of 'startup'. Code:${err.code},message:${err.message}`);
return; return;
} }
console.info("Succeeded in putting the value of 'startup'."); console.info("Succeeded in putting the value of 'startup'.");
preferences.flush((err) => { preferences.flush((err: BusinessError) => {
if (err) { if (err) {
console.error(`Failed to flush. Code:${err.code}, message:${err.message}`); console.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
return; return;
...@@ -207,10 +212,10 @@ The following table lists the APIs used for persisting user preference data. For ...@@ -207,10 +212,10 @@ The following table lists the APIs used for persisting user preference data. For
Example: Example:
```js ```js
try { try {
dataPreferences.deletePreferences(this.context, 'mystore', (err, val) => { dataPreferences.deletePreferences(this.context, 'myStore', (err: BusinessError) => {
if (err) { if (err) {
console.error(`Failed to delete preferences. Code:${err.code}, message:${err.message}`); console.error(`Failed to delete preferences. Code:${err.code}, message:${err.message}`);
return; return;
......
...@@ -3,26 +3,30 @@ ...@@ -3,26 +3,30 @@
## When to Use ## When to Use
To implement traditional data synchronization between devices, you need to design the message processing logic, including setting up a communication link, sending, receiving, and processing messages, retry mechanism upon errors, and resolving data conflicts. The workload is heavy. In addition, the debugging complexity increases with the number of devices. The traditional implementation of data synchronization between devices involves heavy workload. You need to design the message processing logic for setting up a communication link, sending, receiving, and processing messages, and resolving data conflicts, as well as retry mechanism upon errors. In addition, the debugging complexity increases with the number of devices.
The device status, message sending progress, and data transmitted are variables. If these variables support global access, they can be accessed as local variables on difference devices. This simplifies data synchronization between multiple devices. The device status, message sending progress, and data transmitted are variables. If these variables support global access, they can be accessed as local variables by difference devices. This simplifies data synchronization across devices.
The distributed data object (**DataObject**) implements global access to variables. **DataObject** provides basic data object management capabilities and distributed capabilities. You can use the APIs to create, query, delete, and modify in-memory objects and subscribe to event notifications. OpenHarmony also provides easy-to-use JS APIs for distributed application scenarios to easily implement cross-device data collaboration for the same application. In addition, object status and data changes on different devices can be observed. This feature implements data object collaboration for the same application between multiple devices that form a Super Device. **DataObject** greatly reduces the development workloads compared with the traditional mode. The distributed data object (**distributedDataObject**) module implements global access to variables. It provides basic data object management capabilities, including creating, querying, deleting, and modifying in-memory objects and subscribing to data or status changes. It also provides distributed capabilities. OpenHarmony provides easy-to-use JS APIs for distributed application scenarios. With these APIs, you can easily implement data collaboration for an application across devices and listening for status and data changes between devices. The **distributedDataObject** module implements data object collaboration for the same application across multiple devices that form a Super Device. It greatly reduces the development workloads compared with the traditional implementation.
## Basic Concepts ## Basic Concepts
- Distributed in-memory database<br> - Distributed in-memory database
The distributed in-memory database caches data in the memory so that applications can quickly access data without persisting data. If the database is closed, the data is not retained.
The distributed in-memory database caches data in the memory so that applications can quickly access data without persisting data. If the database is closed, the data is not retained.
- Distributed data object - Distributed data object
A distributed data object is an encapsulation of the JS object type. Each distributed data object instance creates a data table in the in-memory database. The in-memory databases created for different applications are isolated from each other. Reading data from and writing data to a distributed data object are mapped to the **get()** and **put()** operations in the corresponding database, respectively.
The distributed data object can be in the following states in its lifecycle: A distributed data object is an encapsulation of the JS object type. Each distributed data object instance creates a data table in the in-memory database. The in-memory databases created for different applications are isolated from each other. Reading and writing a distributed data object are mapped to the **get** and **put** operations in the corresponding database, respectively.
- **Uninitialized**: The distributed data object is not instantiated or has been destroyed. The distributed data object has the following states in its lifecycle:
- **Local**: The data table is created, but the data cannot be synchronized.
- **Distributed**: The data table is created, and there are at least two online devices with the same session ID. In this case, data can be synchronized across devices. If a device is offline or the session ID is empty, the distributed data object changes to the local state. - **Uninitialized**: The distributed data object is not instantiated or is destroyed.
- **Local**: A data table is created, but the data cannot be synchronized.
- **Distributed**: A data table is created, and data can be synchronized (there are at least two online devices with the same session ID). If a device is offline or the session ID is empty, the distributed data object changes to the local state.
## Working Principles ## Working Principles
...@@ -31,201 +35,221 @@ The distributed data object (**DataObject**) implements global access to variabl ...@@ -31,201 +35,221 @@ The distributed data object (**DataObject**) implements global access to variabl
![distributedObject](figures/distributedObject.jpg) ![distributedObject](figures/distributedObject.jpg)
The distributed data objects are encapsulated into JS objects in distributed in-memory databases. This allows the distributed data objects to be operated in the same way as local variables. The system automatically implements cross-device data synchronization. The distributed data objects are encapsulated JS objects in distributed in-memory databases, and can be operated in the same way as local variables. The system automatically implements data synchronization across devices.
### JS Object Storage and Encapsulation Mechanism ### Encapsulation and Storage of JS Objects
- An in-memory database is created for each distributed data object instance and identified by a session ID (**SessionId**). The in-memory databases created for different applications are isolated from each other. - An in-memory database is created for each distributed data object instance and identified by a session ID (**SessionId**). The in-memory databases created for different applications are isolated from each other.
- When a distributed data object is instantiated, all properties of the object are traversed recursively. **Object.defineProperty** is used to define the **set()** and **get()** methods of all properties. The **set()** and **get()** methods correspond to the **put** and **get** operations of a record in the database, respectively. **Key** specifies the property name, and **Value** specifies the property value. - When a distributed data object is instantiated, all properties of the object are traversed recursively. **Object.defineProperty** is used to define the **set()** and **get()** methods for all properties. The **set()** and **get()** methods correspond to the **put** and **get** operations of a record in the database, respectively. **Key** specifies the property name, and **Value** specifies the property value.
- When a distributed data object is read or written, the **set()** and **get()** methods are automatically called to perform the related operations to the database. - When a distributed data object is read or written, the **get()** or **set()** method is automatically called to perform the related operation on data in the database.
**Table 1** Correspondence between a distributed data object and a distributed database **Table 1** Correspondence between a distributed data object and a distributed database
| Distributed Data Object Instance| Object Instance| Property Name| Property Value| | Distributed Data Object Instance| Object Instance| Property Name| Property Value|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| Distributed in-memory database| Database identified by **sessionID**| Key of a record in the database| Value of a record in the database| | Distributed in-memory database| Database identified by **sessionID**| Key of a record in the database| Value of a record in the database|
### Cross-Device Synchronization and Data Change Notification Mechanism ### Cross-Device Synchronization and Data Change Notification
The distributed data object is used to implement data synchronization between objects. You can create a distributed data object and set **sessionID** for the devices on a trusted network. The distributed data objects with the same **sessionID** on different devices can synchronize data with each other. One of the most important functions of distributed data objects is to implement data synchronization between objects. Distributed data objects are created locally for the devices on a trusted network. If the distributed data objects on different devices are set with the same **sessionID**, data can be synchronized between them.
As shown in the following figure, distributed data object 1 on device A and device B have the same session ID **session1**. The synchronization relationship of session1 is established between the two objects. As shown in the following figure, distributed data object 1 of device A and distributed data object 1 of device B are set with the same session ID **session1**, and synchronization relationship of session 1 is established between the two objects.
**Figure 2** Object synchronization relationship **Figure 2** Object synchronization relationship
![distributedObject_sync](figures/distributedObject_sync.jpg) ![distributedObject_sync](figures/distributedObject_sync.jpg)
For each device, only one object can be added to a synchronization relationship. As shown in the preceding figure, distributed data object 2 of device A cannot be added to session 1 because distributed data object 1 of device A has been added to session 1. For each device, only one distributed data object can be added to a synchronization relationship. As shown in the preceding figure, distributed data object 2 of device A cannot be added to session 1 because distributed data object 1 of device A has been added to session 1.
After the synchronization relationship is established, each session has a copy of shared object data. The distributed data objects added to a session support the following operations:
After the synchronization relationship is established, each session has a copy of shared object data. The distributed data objects added to the same session support the following operations: - Reading or modifying the data in the session.
(1) Reading or modifying the data in the session. - Listening for data changes made by other devices.
(2) Listening for data changes made by other devices. - Listening for status changes, such as the addition and removal of other devices.
(3) Listening for status changes, such as the addition and removal of other devices.
### Minimum Unit to Synchronize ### Minimum Synchronization Unit
Attribute is the minimum unit to synchronize in distributed data objects. For example, object 1 in the following figure has three attributes: name, age, and parents. If one of the attributes is changed, only the changed attribute needs to be synchronized. Property is the minimum unit to synchronize in distributed data objects. For example, object 1 in the following figure has three properties: name, age, and parents. If one of the properties is changed, only the changed attribute needs to be synchronized.
**Figure 3** Synchronization of distributed data objects **Figure 3** Synchronization of distributed data objects
![distributedObject_syncView](figures/distributedObject_syncView.jpg) ![distributedObject_syncView](figures/distributedObject_syncView.jpg)
### Object Persistence Mechanism ### Persistence of Distributed Data Objects
Distributed data objects run in the process space of applications. When the data of a distributed data object is persisted in the distributed database, the data will not be lost after the application exits. Distributed data objects run in the process space of applications. After the data of a distributed data object is persisted in the distributed database, the data will not be lost after the application exits.
You need to persist distributed data objects in the following scenarios: You need to persist distributed data objects in the following scenarios:
- Enable an application to retrieve the exact same data after it is opened again. In this case, you need to persist the distributed data object (for example, object 1). After the application is opened again, create a distributed data object (for example, object 2) and set the session ID of object 1 for object 2. Then, the application can retrieve the data of object 1. - Enable an application to retrieve the exact same data after it starts again. In this case, you need to persist the distributed data object (for example, object 1 with session ID 1). After the application starts again, create a distributed data object (for example, object 2) and set the session ID to 1. Then, the application can retrieve the data of object 1.
- Enable an application opened on another device to retrieve the exact same data. In this case, you need to persist the distributed data object (for example, object 1) on device A and synchronize the data to device B. Then, create a distributed data object (for example, object 2) and set the session ID of object 1 for object 2. When the application is opened on device B, it can retrieve the same application data used on device A before the application is closed. - Enable an application started on another device to retrieve the exact same data. In this case, you need to persist the distributed data object (for example, object 1 with session ID 1) on device A and synchronize the data to device B. Then, create a distributed data object (for example, object 2) and set the session ID to 1. When the application is started on device B, it can retrieve the same application data used on device A before the application is closed.
## Constraints ## Constraints
- Data synchronization can be implemented across devices only for the applications with the same **bundleName**. - Only the data of the same application can be synchronized across devices, that is, the devices must have the same **bundleName**.
- Data can be synchronized only for the distributed data objects with the same **sessionID** of the same application. - Data can be synchronized for the distributed data objects with the same session ID.
- Each distributed data object occupies 100 KB to 150 KB of memory. Therefore, you are advised not to create too many distributed data objects. - Each distributed data object occupies 100 KB to 150 KB of memory. Therefore, you are advised not to create too many distributed data objects.
- The maximum size of a distributed data object is 500 KB. - The maximum size of a distributed data object is 500 KB.
- It takes about 50 ms from the time when 1 KB of data starts to be modified on a device to the time when another device receives a data change notification. - If data of 1 KB data is modified on device A, device B can complete data update within 50 ms after receiving a data change notification.
- A maximum of 16 distributed data object instances can be created for an application. - A maximum of 16 distributed data object instances can be created for an application.
- For optimal performance and user experience, the maximum number of devices for data collaboration is 3. - For the sake of performance and user experience, the maximum number of devices for data collaboration is 3.
- For the distributed data object of the complex type, only the root attribute can be modified. The subordinate attributes cannot be modified. - For the distributed data object of the complex type, only the root property can be modified. The subordinate properties cannot be modified.
- Only JS APIs are supported. - Currently, only JS APIs are supported.
## Available APIs ## Available APIs
The following table lists the APIs for cross-device synchronization of distributed data objects. Most of the interfaces are executed asynchronously, using a callback or promise to return the result. The following table uses the callback-based APIs as an example. For more information about the APIs, see [Distributed Data Object](../reference/apis/js-apis-data-distributedobject.md). Most of the APIs for cross-device synchronization of distributed data objects are executed asynchronously in callback or promise mode. The following table uses the callback-based APIs as an example. For more information about the APIs, see [Distributed Data Object](../reference/apis/js-apis-data-distributedobject.md).
| API| Description| | API| Description|
| -------- | -------- | | -------- | -------- |
| create(context: Context, source: object): DataObject | Creates a distributed data object instance.| | create(context: Context, source: object): DataObject | Creates a distributed data object instance.|
| genSessionId(): string | Generates a session ID for distributed data objects.| | genSessionId(): string | Generates a session ID for distributed data objects.|
| setSessionId(sessionId: string, callback: AsyncCallback&lt;void&gt;): void | Sets a session ID for data synchronization. Automatic synchronization is performed for devices with the same session ID on a trusted network.| | setSessionId(sessionId: string, callback: AsyncCallback&lt;void&gt;): void | Sets a session ID for data synchronization. Automatic synchronization is performed for devices with the same session ID on a trusted network.|
| setSessionId(callback: AsyncCallback&lt;void&gt;): void | Exits all sessions.| | setSessionId(callback: AsyncCallback&lt;void&gt;): void | Exits all sessions.|
| on(type: 'change', callback: Callback&lt;{ sessionId: string, fields: Array&lt;string&gt; }&gt;): void | Subscribes to data changes of this distributed data object.| | on(type: 'change', callback: Callback&lt;{ sessionId: string, fields: Array&lt;string&gt; }&gt;): void | Subscribes to data changes of this distributed data object.|
| on(type: 'status', callback: Callback&lt;{ sessionId: string, networkId: string, status: 'online' \| 'offline' }&gt;): void | Subscribes to status changes of this distributed data object.| | on(type: 'status', callback: Callback&lt;{ sessionId: string, networkId: string, status: 'online' \| 'offline' }&gt;): void | Subscribes to status changes of this distributed data object.|
| save(deviceId: string, callback: AsyncCallback&lt;SaveSuccessResponse&gt;): void | Saves a distributed data object.| | save(deviceId: string, callback: AsyncCallback&lt;SaveSuccessResponse&gt;): void | Saves a distributed data object.|
| revokeSave(callback: AsyncCallback&lt;RevokeSaveSuccessResponse&gt;): void | Revokes the save operation of the distributed data object.| | revokeSave(callback: AsyncCallback&lt;RevokeSaveSuccessResponse&gt;): void | Revokes the saving of the distributed data object.|
## How to Develop ## How to Develop
The following example demonstrates how to implement a distributed data object synchronization. The following example demonstrates how to implement synchronization of distributed data objects.
1. Import the **@ohos.data.distributedDataObject** module. 1. Import the **@ohos.data.distributedDataObject** module.
```js ```js
import distributedDataObject from '@ohos.data.distributedDataObject'; import distributedDataObject from '@ohos.data.distributedDataObject';
``` ```
2. Request permissions. 2. Apply for required permissions.
1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). 1. Apply for the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
2. Display a dialog box to ask authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization). 2. Display a dialog box to ask authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization).
3. Creates a distributed data object instance. 3. Create a distributed data object instance.
Stage model: Stage model:
```js ```js
// Import the module. // Import the module.
import distributedDataObject from '@ohos.data.distributedDataObject'; import distributedDataObject from '@ohos.data.distributedDataObject';
import UIAbility from '@ohos.app.ability.UIAbility'; 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 { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage: window.WindowStage) {
// Create a distributed data object, which contains attributes of the string, number, boolean, and object types. let source: sourceObject = {
let localObject = distributedDataObject.create(this.context, {
name: 'jack', name: 'jack',
age: 18, age: 18,
isVis: false, isVis: false,
parent: { mother: 'jack mom', father: 'jack Dad' }, parent: { mother: 'jack mom', father: 'jack Dad' },
list: [{ mother: 'jack mom' }, { father: 'jack Dad' }] list: [{ mother: 'jack mom' }, { father: 'jack Dad' }]
}); }
let localObject: distributedDataObject.DataObject = distributedDataObject.create(this.context, source);
} }
} }
``` ```
FA model: FA model:
```js ```js
// Import the module. // Import the module.
import distributedDataObject from '@ohos.data.distributedDataObject'; import distributedDataObject from '@ohos.data.distributedDataObject';
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
// Obtain the context. // Obtain the context.
let context = featureAbility.getContext(); let context = featureAbility.getContext();
// Create a distributed data object, which contains attributes of the string, number, boolean, and object types. interface sourceObject{
let localObject = distributedDataObject.create(context, { name: string,
age: number,
isVis: boolean
parent: { [key: string]: string },
list: { [key: string]: string }[]
}
let source: sourceObject = {
name: 'jack', name: 'jack',
age: 18, age: 18,
isVis: false, isVis: false,
parent: { mother: 'jack mom', father: 'jack Dad' }, parent: { mother: 'jack mom', father: 'jack Dad' },
list: [{ mother: 'jack mom' }, { father: 'jack Dad' }] list: [{ mother: 'jack mom' }, { father: 'jack Dad' }]
}); }
// Create a distributed data object, which has properties of the string, number, boolean, and object types.
let localObject: distributedDataObject.DataObject = distributedDataObject.create(context, source);
``` ```
4. Set the same session ID for the distributed data objects for data synchronization. The data objects in the synchronization network include the local and remote objects. 4. Set the same session ID for the distributed data objects for data synchronization. The data objects in the synchronization network include the local and remote objects.
```js ```js
// Set a session ID, for example, 123456, for device 1. // Set a session ID, for example, 123456, for device 1.
let sessionId = '123456'; let sessionId: string = '123456';
localObject.setSessionId(sessionId); localObject.setSessionId(sessionId);
// Set the same session ID for device 2. // Set the same session ID for device 2.
// Create a distributed data object, which contains attributes of the string, number, boolean, and object types. // Create a distributed data object, which has properties of the string, number, boolean, and object types.
let remoteObject = distributedDataObject.create(this.context, { let remoteSource: sourceObject = {
name: undefined, name: undefined,
age: undefined, // undefined indicates that the data comes from the peer end. age: undefined, // undefined indicates that the data comes from the peer end.
isVis: true, isVis: true,
parent: undefined, parent: undefined,
list: undefined list: undefined
}); }
// After learning that the device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18. let remoteObject: distributedDataObject.DataObject = distributedDataObject.create(this.context, remoteSource);
// After learning that the device goes online, the remote object synchronizes data. That is, name is changed to jack and age to 18.
remoteObject.setSessionId(sessionId); remoteObject.setSessionId(sessionId);
``` ```
5. Observe data changes of a distributed data object. You can subscribe to data changes of the remote object. When the data in the remote object changes, a callback will be invoked to return a data change event. 5. Observe data changes of a distributed data object. You can subscribe to data changes of the remote object. When the data in the remote object changes, a callback will be invoked to return a data change event.
```js
function changeCallback(sessionId, changeData) {
console.info(`change: ${sessionId}`);
if (changeData !== null && changeData !== undefined) { ```js
changeData.forEach(element => { interface ChangeCallback {
console.info(`The element ${localObject[element]} changed.`); sessionId: string,
}); fields: Array<string>
}
} }
// To refresh the page in changeCallback, correctly bind (this) to the changeCallback. localObject.on("change", (changeData:ChangeCallback) => {
localObject.on("change", this.changeCallback.bind(this)); 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.`);
}
}
});
``` ```
6. Modify attributes of the distributed data object. The object attributes support basic data types (number, Boolean, and string) and complex data types (array and nested basic types). 6. Modify properties of the distributed data object. The object properties support basic data types (number, Boolean, and string) and complex data types (array and nested basic types).
```js ```js
localObject.name = 'jack1'; localObject.name = 'jack1';
localObject.age = 19; localObject.age = 19;
...@@ -236,9 +260,9 @@ The following example demonstrates how to implement a distributed data object sy ...@@ -236,9 +260,9 @@ The following example demonstrates how to implement a distributed data object sy
> **NOTE** > **NOTE**
> >
> For the distributed data object of the complex type, only the root attribute can be modified. The subordinate attributes cannot be modified. > For the distributed data object of the complex type, only the root property can be modified. The subordinate properties cannot be modified.
```js ```js
// Supported modification. // Supported modification.
localObject.parent = { mother: 'mom', father: 'dad' }; localObject.parent = { mother: 'mom', father: 'dad' };
...@@ -246,62 +270,82 @@ The following example demonstrates how to implement a distributed data object sy ...@@ -246,62 +270,82 @@ The following example demonstrates how to implement a distributed data object sy
localObject.parent.mother = 'mom'; localObject.parent.mother = 'mom';
``` ```
7. Access a distributed data object. Obtain the distributed data object attributes, which are the latest data on the network. 7. Access a distributed data object. Obtain the distributed data object properties, which are the latest data on the network.
```js ```js
console.info(`name:${localObject['name']}`); console.info(`name:${localObject['name']}`);
``` ```
8. Unsubscribe from data changes. You can specify the callback to unregister. If you do not specify the callback, all data change callbacks of the distributed data object will be unregistered. 8. Unsubscribe from data changes. You can specify the callback to unregister. If you do not specify the callback, this API unregisters all data change callbacks of the distributed data object.
```js ```js
// Unregister this.changeCallback. // Unregister this.changeCallback.
localObject.off('change', this.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]]);
}
}
});
// Unregister all data change callbacks. // Unregister all data change callbacks.
localObject.off('change'); localObject.off('change');
``` ```
9. Subscribes to status changes of a distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline. 9. Subscribe to status changes of a distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline.
```js ```js
function statusCallback(sessionId, networkId, status) { interface onStatusCallback {
// Service processing. sessionId: string,
networkId: string,
status: 'online' | 'offline'
} }
localObject.on('status', this.statusCallback); localObject.on('status', (statusCallback: onStatusCallback) => {
console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.networkId);
// Service processing.
});
``` ```
10. Save a distributed data object and revoke the data saving operation. 10. Save a distributed data object and revoke the data saved.
```js ```js
// Save the data object if the device on the network needs to retrieve the object data after the application exits. // Save the data object if the device on the network needs to retrieve the object data after the application exits.
localObject.save('local').then((result) => { localObject.save("local").then((result: distributedDataObject.SaveSuccessResponse) => {
console.info(`Succeeded in saving. SessionId:${result.sessionId},version:${result.version},deviceId:${result.deviceId}`); console.info(`Succeeded in saving. SessionId:${result.sessionId},version:${result.version},deviceId:${result.deviceId}`);
}).catch((err) => { }).catch((err: BusinessError) => {
console.error(`Failed to save. Code:${err.code},message:${err.message}`); console.error(`Failed to save. Code:${err.code},message:${err.message}`);
}); });
// Revoke the save of a distributed data object. // Revoke the data saved.
localObject.revokeSave().then((result) => { localObject.revokeSave().then((result: distributedDataObject.RevokeSaveSuccessResponse) => {
console.info(`Succeeded in revokeSaving. Session:${result.sessionId}`); console.info(`Succeeded in revokeSaving. Session:${result.sessionId}`);
}).catch((err) => { }).catch((err: BusinessError) => {
console.error(`Failed to revokeSave. Code:${err.code},message:${err.message}`); console.error(`Failed to revokeSave. Code:${err.code},message:${err.message}`);
}); });
``` ```
11. Unsubscribe from the status changes of a distributed data object. You can specify the callback to unregister. If you do not specify the callback, this API unregisters all status change callbacks of this distributed data object. 11. Unsubscribe from the status changes of a distributed data object. You can specify the callback to unregister. If you do not specify the callback, this API unregisters all status change callbacks of this distributed data object.
```js ```js
interface offStatusCallback {
sessionId: string,
deviceId: string,
status: 'online' | 'offline'
}
// Unregister this.statusCallback. // Unregister this.statusCallback.
localObject.off('status', this.statusCallback); localObject.off('status', (statusCallback: offStatusCallback) => {
console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.deviceId);
// Service processing.
});
// Unregister all status change callbacks. // Unregister all status change callbacks.
localObject.off('status'); localObject.off('status');
``` ```
12. Remove a distributed data object from the synchronization network. The data of the removed distributed data object will not be synchronized to other devices. 12. Remove a distributed data object from the synchronization network. The data of the removed distributed data object will not be synchronized to other devices.
```js ```js
localObject.setSessionId(() => { localObject.setSessionId(() => {
console.info('leave all lession.'); console.info('leave all session.');
}); });
``` ```
\ No newline at end of file
...@@ -23,10 +23,10 @@ Creates a distributed data object. ...@@ -23,10 +23,10 @@ Creates a distributed data object.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context | Context | Yes| Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| | context | Context | Yes| Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).|
| source | object | Yes| Attributes of the distributed data object.| | source | object | Yes| Attributes of the distributed data object.|
**Return value** **Return value**
...@@ -42,10 +42,20 @@ FA model: ...@@ -42,10 +42,20 @@ FA model:
// Import the module. // Import the module.
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base';
// Obtain the context. // Obtain the context.
let context = featureAbility.getContext(); let context = featureAbility.getContext();
// Create a distributed data object, which contains attributes of the string, number, boolean, and object types. interface sourceObject{
let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); name: string,
age: number,
isVis: boolean
}
let source: sourceObject = {
name: "amy",
age:18,
isVis:false
}
let g_object: distributedObject.DataObject = distributedObject.create(context, source);
``` ```
Stage model: Stage model:
...@@ -54,13 +64,23 @@ Stage model: ...@@ -54,13 +64,23 @@ Stage model:
// Import the module. // Import the module.
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base';
let g_object = null; import window from '@ohos.window';
let g_object: distributedObject.DataObject = null;
interface sourceObject{
name: string,
age: number,
isVis: boolean
}
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage: window.WindowStage) {
// Create a distributed data object, which has attributes of the string, number, boolean, and object types. let source: sourceObject = {
g_object = distributedObject.create(this.context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); name: "amy",
age:18,
isVis:false
}
g_object = distributedObject.create(this.context, source);
} }
} }
``` ```
...@@ -75,15 +95,15 @@ Creates a random session ID. ...@@ -75,15 +95,15 @@ Creates a random session ID.
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| string | Session ID created.| | string | Session ID created.|
**Example** **Example**
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
let sessionId = distributedObject.genSessionId(); let sessionId: string = distributedObject.genSessionId();
``` ```
## SaveSuccessResponse<sup>9+</sup> ## SaveSuccessResponse<sup>9+</sup>
...@@ -124,18 +144,18 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo ...@@ -124,18 +144,18 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| sessionId | string | Yes| ID of a distributed data object on a trusted network.| | sessionId | string | Yes| ID of a distributed data object on a trusted network.|
| callback | AsyncCallback&lt;void&gt; | Yes| Asynchronous callback invoked when the session ID is successfully set.| | callback | AsyncCallback&lt;void&gt; | Yes| Asynchronous callback invoked when the session ID is successfully set.|
**Error codes** **Error codes**
For details about the error codes, see [Distributed Data Object Error Codes](../errorcodes/errorcode-distributed-dataObject.md). For details about the error codes, see [Distributed Data Object Error Codes](../errorcodes/errorcode-distributed-dataObject.md).
| ID| Error Message| | ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 15400001 | Create table failed.| | 15400001 | Create table failed.|
**Example** **Example**
...@@ -158,17 +178,17 @@ Exits all joined sessions. ...@@ -158,17 +178,17 @@ Exits all joined sessions.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Asynchronous callback invoked when the distributed data object exits all joined sessions.| | callback | AsyncCallback&lt;void&gt; | Yes| Asynchronous callback invoked when the distributed data object exits all joined sessions.|
**Error codes** **Error codes**
For details about the error codes, see [Distributed Data Object Error Codes](../errorcodes/errorcode-distributed-dataObject.md). For details about the error codes, see [Distributed Data Object Error Codes](../errorcodes/errorcode-distributed-dataObject.md).
| ID| Error Message| | ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 15400001 | Create table failed.| | 15400001 | Create table failed.|
**Example** **Example**
...@@ -179,7 +199,7 @@ g_object.setSessionId(distributedObject.genSessionId(), ()=>{ ...@@ -179,7 +199,7 @@ g_object.setSessionId(distributedObject.genSessionId(), ()=>{
}); });
// Exit the distributed network. // Exit the distributed network.
g_object.setSessionId(() => { g_object.setSessionId(() => {
console.info("leave all lession."); console.info("leave all session.");
}); });
``` ```
...@@ -195,9 +215,9 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo ...@@ -195,9 +215,9 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| | sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
**Return value** **Return value**
...@@ -209,9 +229,9 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo ...@@ -209,9 +229,9 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo
For details about the error codes, see [Distributed Data Object Error Codes](../errorcodes/errorcode-distributed-dataObject.md). For details about the error codes, see [Distributed Data Object Error Codes](../errorcodes/errorcode-distributed-dataObject.md).
| ID| Error Message| | ID| Error Message|
| -------- | -------- | | -------- | -------- |
| 15400001 | Create table failed.| | 15400001 | Create table failed.|
**Example** **Example**
...@@ -219,13 +239,13 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo ...@@ -219,13 +239,13 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo
// Add g_object to the distributed network. // Add g_object to the distributed network.
g_object.setSessionId(distributedObject.genSessionId()).then (()=>{ g_object.setSessionId(distributedObject.genSessionId()).then (()=>{
console.info("join session."); console.info("join session.");
}).catch((error)=>{ }).catch((error: BusinessError)=>{
console.info("error:" + error.code + error.message); console.info("error:" + error.code + error.message);
}); });
// Exit the distributed network. // Exit the distributed network.
g_object.setSessionId().then (()=>{ g_object.setSessionId().then (()=>{
console.info("leave all lession."); console.info("leave all session.");
}).catch((error)=>{ }).catch((error: BusinessError)=>{
console.info("error:" + error.code + error.message); console.info("error:" + error.code + error.message);
}); });
``` ```
...@@ -240,23 +260,26 @@ Subscribes to data changes of this distributed data object. ...@@ -240,23 +260,26 @@ Subscribes to data changes of this distributed data object.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.| | type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | Yes| Callback invoked to return the changes of the distributed data object.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.| | callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | Yes| Callback invoked to return the changes of the distributed data object.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
**Example** **Example**
```js ```js
globalThis.changeCallback = (sessionId, changeData) => { interface ChangeCallback {
console.info("change" + sessionId); sessionId: string,
if (changeData != null && changeData != undefined) { fields: Array<string>
changeData.forEach(element => {
console.info("changed !" + element + " " + g_object[element]);
});
}
} }
g_object.on("change", globalThis.changeCallback); 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]]);
}
}
});
``` ```
### off('change')<sup>9+</sup> ### off('change')<sup>9+</sup>
...@@ -269,17 +292,24 @@ Unsubscribes from the data changes of this distributed data object. ...@@ -269,17 +292,24 @@ Unsubscribes from the data changes of this distributed data object.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.| | type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | No| Callback for data changes. If this parameter is not specified, all data change callbacks of this distributed data object will be unregistered.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.| | callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | No| Callback for data changes. If this parameter is not specified, all data change callbacks of this distributed data object will be unregistered.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
**Example** **Example**
```js ```js
// Unregister the specified data change callback. // Unregister the specified data change callback.
g_object.off("change", globalThis.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]]);
}
}
});
// Unregister all data change callbacks. // Unregister all data change callbacks.
g_object.off("change"); g_object.off("change");
``` ```
...@@ -294,18 +324,23 @@ Subscribes to status changes of this distributed data object. ...@@ -294,18 +324,23 @@ Subscribes to status changes of this distributed data object.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| | type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback invoked to return the status change.<br>**sessionId** indicates the session ID of the distributed data object.<br>**networkId** indicates the object device ID, that is, **deviceId**.<br>**status** indicates the object status, which can be online or offline.| | callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback invoked to return the status change.<br>**sessionId** indicates the session ID of the distributed data object.<br>**networkId** indicates the object device ID, that is, **deviceId**.<br>**status** indicates the object status, which can be online or offline.|
**Example** **Example**
```js ```js
globalThis.statusCallback = (sessionId, networkId, status) => { interface onStatusCallback {
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; sessionId: string,
networkId: string,
status: 'online' | 'offline'
} }
g_object.on("status", globalThis.statusCallback);
g_object.on("status", (statusCallback:onStatusCallback) => {
console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.networkId);
});
``` ```
### off('status')<sup>9+</sup> ### off('status')<sup>9+</sup>
...@@ -318,20 +353,24 @@ Unsubscribes from the status change of this distributed data object. ...@@ -318,20 +353,24 @@ Unsubscribes from the status change of this distributed data object.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| | type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback for status changes. If this parameter is not specified, all status change callbacks of this distributed data object will be unsubscribed from.<br>**sessionId** indicates the session ID of the distributed data object.<br>**deviceId** indicates the device ID of the distributed data object.<br>**status** indicates the object status, which can be online or offline.| | callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback for status changes. If this parameter is not specified, all status change callbacks of this distributed data object will be unsubscribed from.<br>**sessionId** indicates the session ID of the distributed data object.<br>**deviceId** indicates the device ID of the distributed data object.<br>**status** indicates the object status, which can be online or offline.|
**Example** **Example**
```js ```js
globalThis.statusCallback = (sessionId, networkId, status) => { interface offStatusCallback {
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; sessionId: string,
networkId: string,
status: 'online' | 'offline'
} }
// Unregister the specified status change callback. // Unregister the specified status change callback.
g_object.off("status",globalThis.statusCallback); g_object.off("status", (statusCallback:StatusCallback) => {
console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.networkId);
});
// Unregister all status change callbacks. // Unregister all status change callbacks.
g_object.off("status"); g_object.off("status");
``` ```
...@@ -354,16 +393,16 @@ The saved data will be released in the following cases: ...@@ -354,16 +393,16 @@ The saved data will be released in the following cases:
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.| | deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.|
| callback | AsyncCallback&lt;[SaveSuccessResponse](#savesuccessresponse9)&gt; | Yes| Callback invoked to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| | callback | AsyncCallback&lt;[SaveSuccessResponse](#savesuccessresponse9)&gt; | Yes| Callback invoked to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
**Example** **Example**
```ts ```ts
g_object.setSessionId("123456"); g_object.setSessionId("123456");
g_object.save("local", (err, result) => { g_object.save("local", (err: BusinessError, result:distributedObject.SaveSuccessResponse) => {
if (err) { if (err) {
console.info("save failed, error code = " + err.code); console.info("save failed, error code = " + err.code);
console.info("save failed, error message: " + err.message); console.info("save failed, error message: " + err.message);
...@@ -394,26 +433,26 @@ The saved data will be released in the following cases: ...@@ -394,26 +433,26 @@ The saved data will be released in the following cases:
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. | | deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. |
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;[SaveSuccessResponse](#savesuccessresponse9)&gt; | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| | Promise&lt;[SaveSuccessResponse](#savesuccessresponse9)&gt; | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
**Example** **Example**
```js ```js
g_object.setSessionId("123456"); g_object.setSessionId("123456");
g_object.save("local").then((result) => { g_object.save("local").then((result: distributedObject.SaveSuccessResponse) => {
console.info("save callback"); console.info("save callback");
console.info("save sessionId " + result.sessionId); console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version); console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId); console.info("save deviceId " + result.deviceId);
}).catch((err) => { }).catch((err: BusinessError) => {
console.info("save failed, error code = " + err.code); console.info("save failed, error code = " + err.code);
console.info("save failed, error message: " + err.message); console.info("save failed, error message: " + err.message);
}); });
...@@ -432,16 +471,16 @@ If the object is stored on another device, the data on the local device will be ...@@ -432,16 +471,16 @@ If the object is stored on another device, the data on the local device will be
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)&gt; | Yes| Callback invoked to return **RevokeSaveSuccessResponse**, which contains the session ID.| | callback | AsyncCallback&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)&gt; | Yes| Callback invoked to return **RevokeSaveSuccessResponse**, which contains the session ID.|
**Example** **Example**
```js ```js
g_object.setSessionId("123456"); g_object.setSessionId("123456");
// Save data for persistence. // Save data for persistence.
g_object.save("local", (err, result) => { g_object.save("local", (err: BusinessError, result: distributedObject.SaveSuccessResponse) => {
if (err) { if (err) {
console.info("save failed, error code = " + err.code); console.info("save failed, error code = " + err.code);
console.info("save failed, error message: " + err.message); console.info("save failed, error message: " + err.message);
...@@ -453,7 +492,7 @@ g_object.save("local", (err, result) => { ...@@ -453,7 +492,7 @@ g_object.save("local", (err, result) => {
console.info("save deviceId: " + result.deviceId); console.info("save deviceId: " + result.deviceId);
}); });
// Delete the persistence data. // Delete the persistence data.
g_object.revokeSave((err, result) => { g_object.revokeSave((err: BusinessError, result: distributedObject.RevokeSaveSuccessResponse) => {
if (err) { if (err) {
console.info("revokeSave failed, error code = " + err.code); console.info("revokeSave failed, error code = " + err.code);
console.info("revokeSave failed, error message: " + err.message); console.info("revokeSave failed, error message: " + err.message);
...@@ -477,29 +516,29 @@ If the object is stored on another device, the data on the local device will be ...@@ -477,29 +516,29 @@ If the object is stored on another device, the data on the local device will be
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)&gt; | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.| | Promise&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)&gt; | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.|
**Example** **Example**
```ts ```ts
g_object.setSessionId("123456"); g_object.setSessionId("123456");
// Save data for persistence. // Save data for persistence.
g_object.save("local").then((result) => { g_object.save("local").then((result: distributedObject.SaveSuccessResponse) => {
console.info("save callback"); console.info("save callback");
console.info("save sessionId " + result.sessionId); console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version); console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId); console.info("save deviceId " + result.deviceId);
}).catch((err) => { }).catch((err: BusinessError) => {
console.info("save failed, error code = " + err.code); console.info("save failed, error code = " + err.code);
console.info("save failed, error message: " + err.message); console.info("save failed, error message: " + err.message);
}); });
// Delete the persistence data. // Delete the persistence data.
g_object.revokeSave().then((result) => { g_object.revokeSave().then((result: distributedObject.RevokeSaveSuccessResponse) => {
console.info("revokeSave callback"); console.info("revokeSave callback");
console.info("sessionId" + result.sessionId); console.info("sessionId" + result.sessionId);
}).catch((err)=> { }).catch((err: BusinessError)=> {
console.info("revokeSave failed, error code = " + err.code); console.info("revokeSave failed, error code = " + err.code);
console.info("revokeSave failed, error message = " + err.message); console.info("revokeSave failed, error message = " + err.message);
}); });
...@@ -520,9 +559,9 @@ Creates a distributed data object. ...@@ -520,9 +559,9 @@ Creates a distributed data object.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| source | object | Yes| Attributes of the distributed data object.| | source | object | Yes| Attributes of the distributed data object.|
**Return value** **Return value**
...@@ -534,8 +573,17 @@ Creates a distributed data object. ...@@ -534,8 +573,17 @@ Creates a distributed data object.
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
// Create a distributed data object, which contains attributes of the string, number, boolean, and object types. interface sourceObject{
let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); name: string,
age: number,
isVis: boolean
}
let source: sourceObject = {
name: "amy",
age:18,
isVis:false
}
let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source);
``` ```
## DistributedObject<sup>(deprecated)</sup> ## DistributedObject<sup>(deprecated)</sup>
...@@ -558,21 +606,31 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo ...@@ -558,21 +606,31 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| | sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the session ID is set successfully;<br>returns **false** otherwise. | | boolean | Returns **true** if the session ID is set successfully;<br>returns **false** otherwise. |
**Example** **Example**
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});; 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);
// Add g_object to the distributed network. // Add g_object to the distributed network.
g_object.setSessionId(distributedObject.genSessionId()); g_object.setSessionId(distributedObject.genSessionId());
// Remove g_object from the distributed network. // Remove g_object from the distributed network.
...@@ -593,25 +651,38 @@ Subscribes to data changes of this distributed data object. ...@@ -593,25 +651,38 @@ Subscribes to data changes of this distributed data object.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.| | type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | Yes| Callback invoked to return the changes of the distributed data object.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.| | callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | Yes| Callback invoked to return the changes of the distributed data object.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
**Example** **Example**
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); interface sourceObject{
globalThis.changeCallback = (sessionId, changeData) => { name: string,
console.info("change" + sessionId); age: number,
if (changeData != null && changeData != undefined) { isVis: boolean
changeData.forEach(element => { }
console.info("changed !" + element + " " + g_object[element]); interface ChangeCallback {
}); sessionId: string,
} fields: Array<string>
} }
g_object.on("change", globalThis.changeCallback); 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]]);
}
}
});
``` ```
### off('change')<sup>(deprecated)</sup> ### off('change')<sup>(deprecated)</sup>
...@@ -628,19 +699,40 @@ Unsubscribes from the data changes of this distributed data object. ...@@ -628,19 +699,40 @@ Unsubscribes from the data changes of this distributed data object.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.| | type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | No| Callback for data changes. If this parameter is not specified, all data change callbacks of this distributed data object will be unregistered.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.| | callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | No| Callback for data changes. If this parameter is not specified, all data change callbacks of this distributed data object will be unregistered.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
**Example** **Example**
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); interface sourceObject{
name: string,
age: number,
isVis: boolean
}
interface ChangeCallback {
sessionId: string,
fields: Array<string>
}
let source: sourceObject = {
name: "amy",
age:18,
isVis:false
}
let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source);
// Unregister the specified data change callback. // Unregister the specified data change callback.
g_object.off("change", globalThis.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]]);
}
}
});
// Unregister all data change callbacks. // Unregister all data change callbacks.
g_object.off("change"); g_object.off("change");
``` ```
...@@ -659,20 +751,36 @@ Subscribes to status changes of this distributed data object. ...@@ -659,20 +751,36 @@ Subscribes to status changes of this distributed data object.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| | type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback invoked to return the status change.<br>**sessionId** indicates the session ID of the distributed data object.<br>**networkId** indicates the object device ID, that is, **deviceId**.<br>**status** indicates the object status, which can be online or offline.| | callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback invoked to return the status change.<br>**sessionId** indicates the session ID of the distributed data object.<br>**networkId** indicates the object device ID, that is, **deviceId**.<br>**status** indicates the object status, which can be online or offline.|
**Example** **Example**
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
globalThis.statusCallback = (sessionId, networkId, status) => {
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; 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
} }
let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); let g_object: distributedObject.DistributedObject = distributedObject.createDistributedObject(source);
g_object.on("status", globalThis.statusCallback);
g_object.on("status", (statusCallback:StatusCallback) => {
console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.networkId);
});
``` ```
### off('status')<sup>(deprecated)</sup> ### off('status')<sup>(deprecated)</sup>
...@@ -689,8 +797,8 @@ Unsubscribes from the status change of this distributed data object. ...@@ -689,8 +797,8 @@ Unsubscribes from the status change of this distributed data object.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| | type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback for status changes. If this parameter is not specified, all status change callbacks of this distributed data object will be unregistered.<br>**sessionId** indicates the session ID of the distributed data object.<br>**deviceId** indicates the device ID of the distributed data object.<br>**status** indicates the object status, which can be online or offline.| | callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback for status changes. If this parameter is not specified, all status change callbacks of this distributed data object will be unregistered.<br>**sessionId** indicates the session ID of the distributed data object.<br>**deviceId** indicates the device ID of the distributed data object.<br>**status** indicates the object status, which can be online or offline.|
...@@ -699,12 +807,26 @@ Unsubscribes from the status change of this distributed data object. ...@@ -699,12 +807,26 @@ Unsubscribes from the status change of this distributed data object.
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); interface sourceObject{
globalThis.statusCallback = (sessionId, networkId, status) => { name: string,
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; age: number,
isVis: boolean
}
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);
// Unregister the specified status change callback. // Unregister the specified status change callback.
g_object.off("status",globalThis.statusCallback); g_object.off("status", (statusCallback:offStatusCallback) => {
console.info("status changed " + statusCallback.sessionId + " " + statusCallback.status + " " + statusCallback.deviceId);
});
// Unregister all status change callbacks. // Unregister all status change callbacks.
g_object.off("status"); g_object.off("status");
``` ```
...@@ -49,11 +49,13 @@ FA model: ...@@ -49,11 +49,13 @@ FA model:
```js ```js
// Obtain the context. // Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base';
let context = featureAbility.getContext(); let context = featureAbility.getContext();
let preferences = null; let preferences: data_preferences.Preferences = null;
try { try {
data_preferences.getPreferences(context, 'mystore', function (err, val) { data_preferences.getPreferences(context, 'myStore', (err: BusinessError, val: data_preferences.Preferences) => {
if (err) { if (err) {
console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
return; return;
...@@ -70,16 +72,18 @@ Stage model: ...@@ -70,16 +72,18 @@ Stage model:
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base';
import window from '@ohos.window';
let preferences = null; let preferences: data_preferences.Preferences = null;
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage: window.WindowStage) {
try { try {
data_preferences.getPreferences(this.context, 'mystore', function (err, val) { data_preferences.getPreferences(this.context, 'myStore', (err: BusinessError, val: data_preferences.Preferences) => {
if (err) { if (err) {
console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
return; return;
} }
preferences = val; preferences = val;
console.info("Succeeded in getting preferences."); console.info("Succeeded in getting preferences.");
...@@ -119,15 +123,17 @@ FA model: ...@@ -119,15 +123,17 @@ FA model:
```js ```js
// Obtain the context. // Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'
let context = featureAbility.getContext(); let context = featureAbility.getContext();
let preferences = null; let preferences: data_preferences.Preferences = null;
try { try {
let promise = data_preferences.getPreferences(context, 'mystore'); let promise = data_preferences.getPreferences(context, 'myStore');
promise.then((object) => { promise.then((object: data_preferences.Preferences) => {
preferences = object; preferences = object;
console.info("Succeeded in getting preferences."); console.info("Succeeded in getting preferences.");
}).catch((err) => { }).catch((err: BusinessError) => {
console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
}) })
} catch(err) { } catch(err) {
...@@ -139,17 +145,19 @@ Stage model: ...@@ -139,17 +145,19 @@ Stage model:
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';
let preferences = null; let preferences: data_preferences.Preferences = null;
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage: window.WindowStage) {
try { try {
let promise = data_preferences.getPreferences(this.context, 'mystore'); let promise = data_preferences.getPreferences(this.context, 'myStore');
promise.then((object) => { promise.then((object: data_preferences.Preferences) => {
preferences = object; preferences = object;
console.info("Succeeded in getting preferences."); console.info("Succeeded in getting preferences.");
}).catch((err) => { }).catch((err: BusinessError) => {
console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
}) })
} catch(err) { } catch(err) {
...@@ -191,11 +199,14 @@ FA model: ...@@ -191,11 +199,14 @@ FA model:
```js ```js
// Obtain the context. // Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'
let context = featureAbility.getContext(); let context = featureAbility.getContext();
let preferences = null; let preferences: data_preferences.Preferences = null;
try { try {
data_preferences.getPreferences(context, { name: 'mystore' }, function (err, val) { let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' };
data_preferences.getPreferences(context, options, (err: BusinessError, val: data_preferences.Preferences) => {
if (err) { if (err) {
console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
return; return;
...@@ -213,13 +224,16 @@ Stage model: ...@@ -213,13 +224,16 @@ Stage model:
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';
let preferences = null; let preferences: data_preferences.Preferences = null;
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage: window.WindowStage) {
try { try {
data_preferences.getPreferences(this.context, { name: 'mystore', dataGroupId:'myId' }, function (err, val) { let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' };
data_preferences.getPreferences(this.context, options, (err: BusinessError, val: data_preferences.Preferences) => {
if (err) { if (err) {
console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
return; return;
...@@ -271,15 +285,17 @@ FA model: ...@@ -271,15 +285,17 @@ FA model:
```js ```js
// Obtain the context. // Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'
let context = featureAbility.getContext(); let context = featureAbility.getContext();
let preferences = null; let preferences: data_preferences.Preferences = null;
try { try {
let promise = data_preferences.getPreferences(context, { name: 'mystore' }); let options: data_preferences.Options = { name: 'myStore' };
promise.then((object) => { let promise = data_preferences.getPreferences(context, options);
promise.then((object: data_preferences.Preferences) => {
preferences = object; preferences = object;
console.info("Succeeded in getting preferences."); console.info("Succeeded in getting preferences.");
}).catch((err) => { }).catch((err: BusinessError) => {
console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
}) })
} catch(err) { } catch(err) {
...@@ -291,17 +307,20 @@ Stage model: ...@@ -291,17 +307,20 @@ Stage model:
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';
let preferences = null; let preferences: data_preferences.Preferences = null;
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage: window.WindowStage) {
try { try {
let promise = data_preferences.getPreferences(this.context, { name: 'mystore', dataGroupId:'myId' }); let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' };
promise.then((object) => { let promise = data_preferences.getPreferences(this.context, options);
promise.then((object: data_preferences.Preferences) => {
preferences = object; preferences = object;
console.info("Succeeded in getting preferences."); console.info("Succeeded in getting preferences.");
}).catch((err) => { }).catch((err: BusinessError) => {
console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
}) })
} catch(err) { } catch(err) {
...@@ -311,7 +330,6 @@ class EntryAbility extends UIAbility { ...@@ -311,7 +330,6 @@ class EntryAbility extends UIAbility {
} }
``` ```
## data_preferences.deletePreferences ## data_preferences.deletePreferences
deletePreferences(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void deletePreferences(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void
...@@ -345,10 +363,12 @@ FA model: ...@@ -345,10 +363,12 @@ FA model:
```js ```js
// Obtain the context. // Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'
let context = featureAbility.getContext(); let context = featureAbility.getContext();
try { try {
data_preferences.deletePreferences(context, 'mystore', function (err) { data_preferences.deletePreferences(context, 'myStore', (err: BusinessError) => {
if (err) { if (err) {
console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
return; return;
...@@ -364,11 +384,13 @@ Stage model: ...@@ -364,11 +384,13 @@ Stage model:
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage: window.WindowStage) {
try { try {
data_preferences.deletePreferences(this.context, 'mystore', function (err) { data_preferences.deletePreferences(this.context, 'myStore', (err: BusinessError) => {
if (err) { if (err) {
console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
return; return;
...@@ -420,13 +442,15 @@ FA model: ...@@ -420,13 +442,15 @@ FA model:
```js ```js
// Obtain the context. // Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'
let context = featureAbility.getContext(); let context = featureAbility.getContext();
try { try {
let promise = data_preferences.deletePreferences(context, 'mystore'); let promise = data_preferences.deletePreferences(context, 'myStore');
promise.then(() => { promise.then(() => {
console.info("Succeeded in deleting preferences."); console.info("Succeeded in deleting preferences.");
}).catch((err) => { }).catch((err: BusinessError) => {
console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
}) })
} catch(err) { } catch(err) {
...@@ -438,14 +462,16 @@ Stage model: ...@@ -438,14 +462,16 @@ Stage model:
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage: window.WindowStage) {
try{ try{
let promise = data_preferences.deletePreferences(this.context, 'mystore'); let promise = data_preferences.deletePreferences(this.context, 'myStore');
promise.then(() => { promise.then(() => {
console.info("Succeeded in deleting preferences."); console.info("Succeeded in deleting preferences.");
}).catch((err) => { }).catch((err: BusinessError) => {
console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
}) })
} catch(err) { } catch(err) {
...@@ -490,10 +516,13 @@ FA model: ...@@ -490,10 +516,13 @@ FA model:
```js ```js
// Obtain the context. // Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'
let context = featureAbility.getContext(); let context = featureAbility.getContext();
try { try {
data_preferences.deletePreferences(context, { name: 'mystore' }, function (err) { let options: data_preferences.Options = { name: 'myStore' };
data_preferences.deletePreferences(context, options, (err: BusinessError) => {
if (err) { if (err) {
console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
return; return;
...@@ -509,11 +538,14 @@ Stage model: ...@@ -509,11 +538,14 @@ Stage model:
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage: window.WindowStage) {
try { try {
data_preferences.deletePreferences(this.context, { name: 'mystore', dataGroupId:'myId' }, function (err) { let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' };
data_preferences.deletePreferences(this.context, options, (err: BusinessError) => {
if (err) { if (err) {
console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
return; return;
...@@ -568,13 +600,16 @@ FA model: ...@@ -568,13 +600,16 @@ FA model:
```js ```js
// Obtain the context. // Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'
let context = featureAbility.getContext(); let context = featureAbility.getContext();
try { try {
let promise = data_preferences.deletePreferences(context, { name: 'mystore' }); let options: data_preferences.Options = { name: 'myStore' };
let promise = data_preferences.deletePreferences(context, options);
promise.then(() => { promise.then(() => {
console.info("Succeeded in deleting preferences."); console.info("Succeeded in deleting preferences.");
}).catch((err) => { }).catch((err: BusinessError) => {
console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
}) })
} catch(err) { } catch(err) {
...@@ -586,14 +621,17 @@ Stage model: ...@@ -586,14 +621,17 @@ Stage model:
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage: window.WindowStage) {
try{ try{
let promise = data_preferences.deletePreferences(this.context, { name: 'mystore', dataGroupId:'myId' }); let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' };
let promise = data_preferences.deletePreferences(this.context, options);
promise.then(() => { promise.then(() => {
console.info("Succeeded in deleting preferences."); console.info("Succeeded in deleting preferences.");
}).catch((err) => { }).catch((err: BusinessError) => {
console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
}) })
} catch(err) { } catch(err) {
...@@ -631,9 +669,11 @@ FA model: ...@@ -631,9 +669,11 @@ FA model:
```js ```js
// Obtain the context. // Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'
let context = featureAbility.getContext(); let context = featureAbility.getContext();
try { try {
data_preferences.removePreferencesFromCache(context, 'mystore', function (err) { data_preferences.removePreferencesFromCache(context, 'myStore', (err: BusinessError) => {
if (err) { if (err) {
console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
return; return;
...@@ -649,11 +689,13 @@ Stage model: ...@@ -649,11 +689,13 @@ Stage model:
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage: window.WindowStage) {
try { try {
data_preferences.removePreferencesFromCache(this.context, 'mystore', function (err) { data_preferences.removePreferencesFromCache(this.context, 'myStore', (err: BusinessError) => {
if (err) { if (err) {
console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
return; return;
...@@ -699,12 +741,14 @@ FA model: ...@@ -699,12 +741,14 @@ FA model:
```js ```js
// Obtain the context. // Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'
let context = featureAbility.getContext(); let context = featureAbility.getContext();
try { try {
let promise = data_preferences.removePreferencesFromCache(context, 'mystore'); let promise = data_preferences.removePreferencesFromCache(context, 'myStore');
promise.then(() => { promise.then(() => {
console.info("Succeeded in removing preferences."); console.info("Succeeded in removing preferences.");
}).catch((err) => { }).catch((err: BusinessError) => {
console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}) })
} catch(err) { } catch(err) {
...@@ -716,14 +760,16 @@ Stage model: ...@@ -716,14 +760,16 @@ Stage model:
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage: window.WindowStage) {
try { try {
let promise = data_preferences.removePreferencesFromCache(this.context, 'mystore'); let promise = data_preferences.removePreferencesFromCache(this.context, 'myStore');
promise.then(() => { promise.then(() => {
console.info("Succeeded in removing preferences."); console.info("Succeeded in removing preferences.");
}).catch((err) => { }).catch((err: BusinessError) => {
console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}) })
} catch(err) { } catch(err) {
...@@ -761,7 +807,7 @@ FA model: ...@@ -761,7 +807,7 @@ FA model:
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context = featureAbility.getContext();
try { try {
data_preferences.removePreferencesFromCacheSync(context, 'mystore'); data_preferences.removePreferencesFromCacheSync(context, 'myStore');
} catch(err) { } catch(err) {
console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
} }
...@@ -773,9 +819,9 @@ Stage model: ...@@ -773,9 +819,9 @@ Stage model:
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage: window.WindowStage) {
try { try {
data_preferences.removePreferencesFromCacheSync(this.context, 'mystore'); data_preferences.removePreferencesFromCacheSync(this.context, 'myStore');
} catch(err) { } catch(err) {
console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
} }
...@@ -819,9 +865,11 @@ FA model: ...@@ -819,9 +865,11 @@ FA model:
```js ```js
// Obtain the context. // Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'
let context = featureAbility.getContext(); let context = featureAbility.getContext();
try { try {
data_preferences.removePreferencesFromCache(context, { name: 'mystore' }, function (err) { let options: data_preferences.Options = { name: 'myStore' };
data_preferences.removePreferencesFromCache(context, options, (err: BusinessError) => {
if (err) { if (err) {
console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
return; return;
...@@ -837,11 +885,14 @@ Stage model: ...@@ -837,11 +885,14 @@ Stage model:
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage: window.WindowStage) {
try { try {
data_preferences.removePreferencesFromCache(this.context, { name: 'mystore', dataGroupId:'myId' }, function (err) { let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' };
data_preferences.removePreferencesFromCache(this.context, options, (err: BusinessError) => {
if (err) { if (err) {
console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
return; return;
...@@ -896,12 +947,14 @@ FA model: ...@@ -896,12 +947,14 @@ FA model:
```js ```js
// Obtain the context. // Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'
let context = featureAbility.getContext(); let context = featureAbility.getContext();
try { try {
let promise = data_preferences.removePreferencesFromCache(context, { name: 'mystore' }); let options: data_preferences.Options = { name: 'myStore' };
let promise = data_preferences.removePreferencesFromCache(context, options);
promise.then(() => { promise.then(() => {
console.info("Succeeded in removing preferences."); console.info("Succeeded in removing preferences.");
}).catch((err) => { }).catch((err: BusinessError) => {
console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}) })
} catch(err) { } catch(err) {
...@@ -913,14 +966,17 @@ Stage model: ...@@ -913,14 +966,17 @@ Stage model:
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage: window.WindowStage) {
try { try {
let promise = data_preferences.removePreferencesFromCache(this.context, { name: 'mystore', dataGroupId:'myId' }); let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' };
let promise = data_preferences.removePreferencesFromCache(this.context, options);
promise.then(() => { promise.then(() => {
console.info("Succeeded in removing preferences."); console.info("Succeeded in removing preferences.");
}).catch((err) => { }).catch((err: BusinessError) => {
console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}) })
} catch(err) { } catch(err) {
...@@ -928,10 +984,6 @@ class EntryAbility extends UIAbility { ...@@ -928,10 +984,6 @@ class EntryAbility extends UIAbility {
} }
} }
} }
```
}
}
}
``` ```
## Options<sup>10+</sup> ## Options<sup>10+</sup>
...@@ -972,7 +1024,7 @@ Obtains the value corresponding to the specified key from the cached **Preferenc ...@@ -972,7 +1024,7 @@ Obtains the value corresponding to the specified key from the cached **Preferenc
```js ```js
try { try {
preferences.get('startup', 'default', function (err, val) { preferences.get('startup', 'default', (err: BusinessError, val: data_preferences.ValueType) => {
if (err) { if (err) {
console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
return; return;
...@@ -1011,9 +1063,9 @@ Obtains the value corresponding to the specified key from the cached **Preferenc ...@@ -1011,9 +1063,9 @@ Obtains the value corresponding to the specified key from the cached **Preferenc
```js ```js
try { try {
let promise = preferences.get('startup', 'default'); let promise = preferences.get('startup', 'default');
promise.then((data) => { promise.then((data: data_preferences.ValueType) => {
console.info("Got the value of 'startup'. Data: " + data); console.info("Got the value of 'startup'. Data: " + data);
}).catch((err) => { }).catch((err: BusinessError) => {
console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
}) })
} catch(err) { } catch(err) {
...@@ -1046,7 +1098,7 @@ Obtains the value corresponding to the specified key from the cached **Preferenc ...@@ -1046,7 +1098,7 @@ Obtains the value corresponding to the specified key from the cached **Preferenc
```js ```js
try { try {
let value = preferences.getSync('startup', 'default'); let value: data_preferences.ValueType = preferences.getSync('startup', 'default');
console.info("Succeeded in getting value of 'startup'. Data: " + value); console.info("Succeeded in getting value of 'startup'. Data: " + value);
} catch(err) { } catch(err) {
console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
...@@ -1071,14 +1123,14 @@ Obtains all KV pairs from the cached **Preferences** instance. This API uses an ...@@ -1071,14 +1123,14 @@ Obtains all KV pairs from the cached **Preferences** instance. This API uses an
```js ```js
try { try {
preferences.getAll(function (err, value) { preferences.getAll((err: BusinessError, value: data_preferences.ValueType) => {
if (err) { if (err) {
console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message);
return; return;
} }
let allKeys = Object.keys(value); let allKeys = Object.keys(value);
console.info("getAll keys = " + allKeys); console.info("getAll keys = " + allKeys);
console.info("getAll object = " + JSON.stringify(value)); console.info("getAll object = " + JSON.stringify(value));
}) })
} catch (err) { } catch (err) {
console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message);
...@@ -1105,11 +1157,11 @@ Obtains all KV pairs from the cached **Preferences** instance. This API uses a p ...@@ -1105,11 +1157,11 @@ Obtains all KV pairs from the cached **Preferences** instance. This API uses a p
```js ```js
try { try {
let promise = preferences.getAll(); let promise = preferences.getAll();
promise.then((value) => { promise.then((value: data_preferences.ValueType) => {
let allKeys = Object.keys(value); let allKeys = Object.keys(value);
console.info('getAll keys = ' + allKeys); console.info('getAll keys = ' + allKeys);
console.info("getAll object = " + JSON.stringify(value)); console.info("getAll object = " + JSON.stringify(value));
}).catch((err) => { }).catch((err: BusinessError) => {
console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message);
}) })
} catch (err) { } catch (err) {
...@@ -1164,7 +1216,7 @@ Writes data to the cached **Preferences** instance. This API uses an asynchronou ...@@ -1164,7 +1216,7 @@ Writes data to the cached **Preferences** instance. This API uses an asynchronou
```js ```js
try { try {
preferences.put('startup', 'auto', function (err) { preferences.put('startup', 'auto', (err: BusinessError) => {
if (err) { if (err) {
console.error("Failed to put value of 'startup'. code =" + err.code + ", message =" + err.message); console.error("Failed to put value of 'startup'. code =" + err.code + ", message =" + err.message);
return; return;
...@@ -1205,7 +1257,7 @@ try { ...@@ -1205,7 +1257,7 @@ try {
let promise = preferences.put('startup', 'auto'); let promise = preferences.put('startup', 'auto');
promise.then(() => { promise.then(() => {
console.info("Successfully put the value of 'startup'."); console.info("Successfully put the value of 'startup'.");
}).catch((err) => { }).catch((err: BusinessError) => {
console.error("Failed to put value of 'startup'. code =" + err.code +", message =" + err.message); console.error("Failed to put value of 'startup'. code =" + err.code +", message =" + err.message);
}) })
} catch(err) { } catch(err) {
...@@ -1259,7 +1311,7 @@ Checks whether the cached **Preferences** instance contains the KV pair of the g ...@@ -1259,7 +1311,7 @@ Checks whether the cached **Preferences** instance contains the KV pair of the g
```js ```js
try { try {
preferences.has('startup', function (err, val) { preferences.has('startup', (err: BusinessError, val: boolean) => {
if (err) { if (err) {
console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
return; return;
...@@ -1269,7 +1321,7 @@ try { ...@@ -1269,7 +1321,7 @@ try {
} else { } else {
console.info("The key 'startup' is not contained."); console.info("The key 'startup' is not contained.");
} }
}) })
} catch (err) { } catch (err) {
console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
} }
...@@ -1301,15 +1353,15 @@ Checks whether the cached **Preferences** instance contains the KV pair of the g ...@@ -1301,15 +1353,15 @@ Checks whether the cached **Preferences** instance contains the KV pair of the g
```js ```js
try { try {
let promise = preferences.has('startup'); let promise = preferences.has('startup');
promise.then((val) => { promise.then((val: boolean) => {
if (val) { if (val) {
console.info("The key 'startup' is contained."); console.info("The key 'startup' is contained.");
} else { } else {
console.info("The key 'startup' is not contained."); console.info("The key 'startup' is not contained.");
} }
}).catch((err) => { }).catch((err: BusinessError) => {
console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
}) })
} catch(err) { } catch(err) {
console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
} }
...@@ -1340,7 +1392,7 @@ Checks whether the cached **Preferences** instance contains the KV pair of the g ...@@ -1340,7 +1392,7 @@ Checks whether the cached **Preferences** instance contains the KV pair of the g
```js ```js
try { try {
let isExist = preferences.hasSync('startup'); let isExist: boolean = preferences.hasSync('startup');
if (isExist) { if (isExist) {
console.info("The key 'startup' is contained."); console.info("The key 'startup' is contained.");
} else { } else {
...@@ -1371,7 +1423,7 @@ Deletes a KV pair from the cached **Preferences** instance based on the specifie ...@@ -1371,7 +1423,7 @@ Deletes a KV pair from the cached **Preferences** instance based on the specifie
```js ```js
try { try {
preferences.delete('startup', function (err) { preferences.delete('startup', (err: BusinessError) => {
if (err) { if (err) {
console.error("Failed to delete the key 'startup'. code =" + err.code + ", message =" + err.message); console.error("Failed to delete the key 'startup'. code =" + err.code + ", message =" + err.message);
return; return;
...@@ -1411,7 +1463,7 @@ try { ...@@ -1411,7 +1463,7 @@ try {
let promise = preferences.delete('startup'); let promise = preferences.delete('startup');
promise.then(() => { promise.then(() => {
console.info("Deleted the key 'startup'."); console.info("Deleted the key 'startup'.");
}).catch((err) => { }).catch((err: BusinessError) => {
console.error("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message); console.error("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message);
}) })
} catch(err) { } catch(err) {
...@@ -1463,7 +1515,7 @@ Flushes the data in the cached **Preferences** instance to the persistent file. ...@@ -1463,7 +1515,7 @@ Flushes the data in the cached **Preferences** instance to the persistent file.
```js ```js
try { try {
preferences.flush(function (err) { preferences.flush((err: BusinessError) => {
if (err) { if (err) {
console.error("Failed to flush. code =" + err.code + ", message =" + err.message); console.error("Failed to flush. code =" + err.code + ", message =" + err.message);
return; return;
...@@ -1497,7 +1549,7 @@ try { ...@@ -1497,7 +1549,7 @@ try {
let promise = preferences.flush(); let promise = preferences.flush();
promise.then(() => { promise.then(() => {
console.info("Successfully flushed data."); console.info("Successfully flushed data.");
}).catch((err) => { }).catch((err: BusinessError) => {
console.error("Failed to flush. code =" + err.code + ", message =" + err.message); console.error("Failed to flush. code =" + err.code + ", message =" + err.message);
}) })
} catch (err) { } catch (err) {
...@@ -1524,7 +1576,7 @@ Clears all data in the cached **Preferences** instance. This API uses an asynchr ...@@ -1524,7 +1576,7 @@ Clears all data in the cached **Preferences** instance. This API uses an asynchr
```js ```js
try { try {
preferences.clear(function (err) { preferences.clear((err: BusinessError) =>{
if (err) { if (err) {
console.error("Failed to clear. code =" + err.code + ", message =" + err.message); console.error("Failed to clear. code =" + err.code + ", message =" + err.message);
return; return;
...@@ -1558,7 +1610,7 @@ try { ...@@ -1558,7 +1610,7 @@ try {
let promise = preferences.clear(); let promise = preferences.clear();
promise.then(() => { promise.then(() => {
console.info("Successfully cleared data."); console.info("Successfully cleared data.");
}).catch((err) => { }).catch((err: BusinessError) => {
console.error("Failed to clear. code =" + err.code + ", message =" + err.message); console.error("Failed to clear. code =" + err.code + ", message =" + err.message);
}) })
} catch(err) { } catch(err) {
...@@ -1604,29 +1656,31 @@ Subscribes to data changes. A callback will be triggered to return the new value ...@@ -1604,29 +1656,31 @@ Subscribes to data changes. A callback will be triggered to return the new value
**Example** **Example**
```js ```js
interface observer {
key: string
}
try { try {
data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) { data_preferences.getPreferences(this.context, 'myStore', (err: BusinessError, preferences: data_preferences.Preferences) => {
if (err) { if (err) {
console.error("Failed to get preferences."); console.error("Failed to get preferences.");
return; return;
} }
let observer = function (key) { preferences.on('change', (key: observer) => {
console.info("The key " + key + " changed."); console.info("The key " + key + " changed.");
} });
preferences.on('change', observer); preferences.put('startup', 'manual', (err: BusinessError) => {
preferences.put('startup', 'manual', function (err) {
if (err) { if (err) {
console.error("Failed to put the value of 'startup'. Cause: " + err); console.error("Failed to put the value of 'startup'. Cause: " + err);
return; return;
} }
console.info("Successfully put the value of 'startup'."); console.info("Successfully put the value of 'startup'.");
preferences.flush(function (err) { preferences.flush((err: BusinessError) => {
if (err) { if (err) {
console.error("Failed to flush. Cause: " + err); console.error("Failed to flush. Cause: " + err);
return; return;
} }
console.info("Successfully flushed data."); console.info("Successfully flushed data.");
}) })
}) })
}) })
...@@ -1663,24 +1717,26 @@ For details about the error codes, see [User Preference Error Codes](../errorcod ...@@ -1663,24 +1717,26 @@ For details about the error codes, see [User Preference Error Codes](../errorcod
**Example 1** **Example 1**
```js ```js
interface observer {
key: string
}
try { try {
data_preferences.getPreferences(this.context, { name: 'mystore', dataGroupId:'myId' }, function (err, preferences) { let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' };
data_preferences.getPreferences(this.context, options, (err: BusinessError, preferences: data_preferences.Preferences) => {
if (err) { if (err) {
console.error("Failed to get preferences."); console.error("Failed to get preferences.");
return; return;
} }
let observer = function (key) { preferences.on('multiProcessChange', (key: observer) => {
console.info("The key " + key + " changed."); console.info("The key " + key + " changed.");
} });
preferences.on('multiProcessChange', observer); preferences.put('startup', 'manual', (err: BusinessError) => {
preferences.put('startup', 'manual', function (err) {
if (err) { if (err) {
console.error("Failed to put the value of 'startup'. Cause: " + err); console.error("Failed to put the value of 'startup'. Cause: " + err);
return; return;
} }
console.info("Successfully put the value of 'startup'."); console.info("Successfully put the value of 'startup'.");
preferences.flush((err: BusinessError) => {
preferences.flush(function (err) {
if (err) { if (err) {
console.error("Failed to flush. Cause: " + err); console.error("Failed to flush. Cause: " + err);
return; return;
...@@ -1697,17 +1753,21 @@ try { ...@@ -1697,17 +1753,21 @@ try {
**Example 2** **Example 2**
```js ```js
interface observer {
key: string
}
try { try {
data_preferences.getPreferences(this.context, { name: 'mystore' }, function (err, val) { let options: data_preferences.Options = { name: 'myStore' };
data_preferences.getPreferences(this.context, options, (err: BusinessError, val: data_preferences.Preferences) => {
if (err) { if (err) {
console.error("Failed to get preferences."); console.error("Failed to get preferences.");
return; return;
} }
preferences = val; preferences = val;
let observer = function (key) { preferences.on('multiProcessChange', (key: observer) => {
console.info("The key " + key + " changed."); console.info("The key " + key + " changed.");
try { try {
data_preferences.removePreferencesFromCache(this.context, { name: 'mystore' }, function (err) { data_preferences.removePreferencesFromCache(this.context, options, (err: BusinessError) => {
if (err) { if (err) {
console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
return; return;
...@@ -1720,7 +1780,7 @@ try { ...@@ -1720,7 +1780,7 @@ try {
} }
try { try {
data_preferences.getPreferences(this.context, { name: 'mystore' }, function (err, val) { data_preferences.getPreferences(this.context, options, (err: BusinessError, val: data_preferences.Preferences) => {
if (err) { if (err) {
console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
return; return;
...@@ -1731,16 +1791,15 @@ try { ...@@ -1731,16 +1791,15 @@ try {
} catch (err) { } catch (err) {
console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
} }
} });
preferences.on('multiProcessChange', observer); preferences.put('startup', 'manual', (err: BusinessError) => {
preferences.put('startup', 'manual', function (err) {
if (err) { if (err) {
console.error("Failed to put the value of 'startup'. Cause: " + err); console.error("Failed to put the value of 'startup'. Cause: " + err);
return; return;
} }
console.info("Successfully put the value of 'startup'."); console.info("Successfully put the value of 'startup'.");
preferences.flush(function (err) { preferences.flush((err: BusinessError) => {
if (err) { if (err) {
console.error("Failed to flush. Cause: " + err); console.error("Failed to flush. Cause: " + err);
return; return;
...@@ -1772,31 +1831,35 @@ Unsubscribes from data changes. ...@@ -1772,31 +1831,35 @@ Unsubscribes from data changes.
**Example** **Example**
```js ```js
interface observer {
key: string
}
try { try {
data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) { data_preferences.getPreferences(this.context, 'myStore', (err: BusinessError, val: data_preferences.Preferences) => {
if (err) { if (err) {
console.error("Failed to get preferences."); console.error("Failed to get preferences.");
return; return;
} }
let observer = function (key) { preferences.on('change', (key: observer) => {
console.info("The key " + key + " changed."); console.info("The key " + key + " changed.");
} });
preferences.on('change', observer); preferences.put('startup', 'auto', (err: BusinessError) => {
preferences.put('startup', 'auto', function (err) {
if (err) { if (err) {
console.error("Failed to put the value of 'startup'. Cause: " + err); console.error("Failed to put the value of 'startup'. Cause: " + err);
return; return;
} }
console.info("Successfully put the value of 'startup'."); console.info("Successfully put the value of 'startup'.");
preferences.flush(function (err) { preferences.flush((err: BusinessError) =>{
if (err) { if (err) {
console.error("Failed to flush. Cause: " + err); console.error("Failed to flush. Cause: " + err);
return; return;
} }
console.info("Successfully flushed data."); console.info("Successfully flushed data.");
}) })
preferences.off('change', observer); preferences.off('change', (key: observer) => {
console.info("The key " + key + " changed.");
});
}) })
}) })
} catch (err) { } catch (err) {
...@@ -1822,31 +1885,36 @@ Unsubscribes from inter-process data changes. ...@@ -1822,31 +1885,36 @@ Unsubscribes from inter-process data changes.
**Example** **Example**
```js ```js
interface observer {
key: string
}
try { try {
data_preferences.getPreferences(this.context, { name: 'mystore', dataGroupId:'myId' }, function (err, preferences) { let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' };
data_preferences.getPreferences(this.context, options, (err: BusinessError, preferences: data_preferences.Preferences) => {
if (err) { if (err) {
console.error("Failed to get preferences."); console.error("Failed to get preferences.");
return; return;
} }
let observer = function (key) { preferences.on('multiProcessChange', (key: observer) => {
console.info("The key " + key + " changed."); console.info("The key " + key + " changed.");
} });
preferences.on('multiProcessChange', observer); preferences.put('startup', 'auto', (err: BusinessError) => {
preferences.put('startup', 'auto', function (err) {
if (err) { if (err) {
console.error("Failed to put the value of 'startup'. Cause: " + err); console.error("Failed to put the value of 'startup'. Cause: " + err);
return; return;
} }
console.info("Successfully put the value of 'startup'."); console.info("Successfully put the value of 'startup'.");
preferences.flush(function (err) { preferences.flush((err: BusinessError) => {
if (err) { if (err) {
console.error("Failed to flush. Cause: " + err); console.error("Failed to flush. Cause: " + err);
return; return;
} }
console.info("Successfully flushed data."); console.info("Successfully flushed data.");
}) })
preferences.off('multiProcessChange', observer); preferences.off('multiProcessChange', (key: observer) => {
console.info("The key " + key + " changed.");
});
}) })
}) })
} catch (err) { } catch (err) {
......
...@@ -43,11 +43,11 @@ FA model: ...@@ -43,11 +43,11 @@ FA model:
```js ```js
// Obtain the context. // Obtain the context.
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
let context = featureAbility.getContext() let context: Context;
// Call getRdbStore. // Call getRdbStore.
const STORE_CONFIG = { name: "RdbTest.db"} const STORE_CONFIG = { name: "RdbTest.db"}
data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) { data_rdb.getRdbStore(context, STORE_CONFIG, 1, (err, rdbStore) => {
if (err) { if (err) {
console.info("Failed to get RdbStore, err: " + err) console.info("Failed to get RdbStore, err: " + err)
return return
...@@ -61,23 +61,26 @@ Stage model: ...@@ -61,23 +61,26 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from "@ohos.base";
import window from '@ohos.window';
let context; let context: Context;
class EntryAbility extends UIAbility { interface storeConfig {
onWindowStageCreate(windowStage){ name: string
context = this.context
}
} }
// Call getRdbStore. class EntryAbility extends UIAbility {
const STORE_CONFIG = { name: "RdbTest.db"} onWindowStageCreate(windowStage: window.WindowStage){
data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) { let STORE_CONFIG: storeConfig = { name: "RdbTest.db"};
if (err) { data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, (err: BusinessError, rdbStore: data_rdb.RdbStore) => {
if (err) {
console.info("Failed to get RdbStore, err: " + err) console.info("Failed to get RdbStore, err: " + err)
return return
} }
console.log("Got RdbStore successfully.") console.log("Got RdbStore successfully.")
}) })
}
}
``` ```
## data_rdb.getRdbStore ## data_rdb.getRdbStore
...@@ -109,7 +112,7 @@ FA model: ...@@ -109,7 +112,7 @@ FA model:
```js ```js
// Obtain the context. // Obtain the context.
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
let context = featureAbility.getContext() let context: Context;
// Call getRdbStore. // Call getRdbStore.
const STORE_CONFIG = { name: "RdbTest.db" } const STORE_CONFIG = { name: "RdbTest.db" }
...@@ -126,21 +129,26 @@ Stage model: ...@@ -126,21 +129,26 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from "@ohos.base";
import window from '@ohos.window';
let context; let context: Context;
interface storeConfig {
name: string
}
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage: window.WindowStage){
context = this.context context = this.context
} }
} }
// Call getRdbStore. // Call getRdbStore.
const STORE_CONFIG = { name: "RdbTest.db" } let STORE_CONFIG: storeConfig = { name: "RdbTest.db"};
let promise = data_rdb.getRdbStore(context, STORE_CONFIG, 1); let promise = data_rdb.getRdbStore(context, STORE_CONFIG, 1);
promise.then(async (rdbStore) => { promise.then(async (rdbStore: data_rdb.RdbStore) => {
console.log("Got RdbStore successfully.") console.log("Got RdbStore successfully.")
}).catch((err) => { }).catch((err: BusinessError) => {
console.log("Failed to get RdbStore, err: " + err) console.log("Failed to get RdbStore, err: " + err)
}) })
``` ```
...@@ -167,15 +175,15 @@ FA model: ...@@ -167,15 +175,15 @@ FA model:
```js ```js
// Obtain the context. // Obtain the context.
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
let context = featureAbility.getContext() let context: Context;
// Call deleteRdbStore. // Call deleteRdbStore.
data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { data_rdb.deleteRdbStore(context, "RdbTest.db", (err) => {
if (err) { if (err) {
console.info("Failed to delete RdbStore, err: " + err) console.info("Failed to delete RdbStore, err: " + err)
return return
} }
console.log("Deleted RdbStore successfully.") console.log("Deleted RdbStore successfully.")
}) })
``` ```
...@@ -184,21 +192,22 @@ Stage model: ...@@ -184,21 +192,22 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import window from '@ohos.window';
let context; let context: Context;
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage: window.WindowStage){
context = this.context context = this.context
} }
} }
// Call deleteRdbStore. // Call deleteRdbStore.
data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { data_rdb.deleteRdbStore(context, "RdbTest.db", (err) => {
if (err) { if (err) {
console.info("Failed to delete RdbStore, err: " + err) console.info("Failed to delete RdbStore, err: " + err)
return return
} }
console.log("Deleted RdbStore successfully.") console.log("Deleted RdbStore successfully.")
}) })
``` ```
...@@ -230,7 +239,7 @@ FA model: ...@@ -230,7 +239,7 @@ FA model:
```js ```js
// Obtain the context. // Obtain the context.
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
let context = featureAbility.getContext() let context: Context;
// Call deleteRdbStore. // Call deleteRdbStore.
let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") let promise = data_rdb.deleteRdbStore(context, "RdbTest.db")
...@@ -246,20 +255,22 @@ Stage model: ...@@ -246,20 +255,22 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from "@ohos.base";
import window from '@ohos.window';
let context; let context: Context;
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage: window.WindowStage){
context = this.context context = this.context
} }
} }
// Call deleteRdbStore. // Call deleteRdbStore.
let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") let promise = data_rdb.deleteRdbStore(context, "RdbTest.db")
promise.then(()=>{ promise.then(()=>{
console.log("Deleted RdbStore successfully.") console.log("Deleted RdbStore successfully.")
}).catch((err) => { }).catch((err: BusinessError) => {
console.info("Failed to delete RdbStore, err: " + err) console.info("Failed to delete RdbStore, err: " + err)
}) })
``` ```
...@@ -371,8 +382,8 @@ Sets an **RdbPredicates** to specify the remote devices to connect on the networ ...@@ -371,8 +382,8 @@ Sets an **RdbPredicates** to specify the remote devices to connect on the networ
```js ```js
import deviceManager from '@ohos.distributedHardware.deviceManager'; import deviceManager from '@ohos.distributedHardware.deviceManager';
let dmInstance = null; let dmInstance: deviceManager.DeviceManager = null;
let deviceIds = []; let deviceIds: Array<string> = [];
deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => { deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => {
if (err) { if (err) {
...@@ -381,7 +392,7 @@ deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) ...@@ -381,7 +392,7 @@ deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager)
} }
dmInstance = manager; dmInstance = manager;
let devices = dmInstance.getTrustedDeviceListSync(); let devices = dmInstance.getTrustedDeviceListSync();
for (var i = 0; i < devices.length; i++) { for (let i = 0; i < devices.length; i++) {
deviceIds[i] = devices[i].deviceId; deviceIds[i] = devices[i].deviceId;
} }
}) })
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册