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

!9632 修改preference示例代码

Merge pull request !9632 from lijuntao/master
......@@ -94,9 +94,16 @@
```js
// 获取context
import featureAbility from '@ohos.ability.featureAbility'
let context = featureAbility.getContext()
let context = featureAbility.getContext();
let preferences = null;
let promise = data_preferences.getPreferences(context, 'mystore');
promise.then((pref) => {
preferences = pref;
}).catch((err) => {
console.info("Failed to get preferences.");
})
```
Stage模型示例:
......@@ -104,14 +111,21 @@
```ts
// 获取context
import Ability from '@ohos.application.Ability'
let context = null
let context = null;
let preferences = null;
export default class MainAbility extends Ability {
onWindowStageCreate(windowStage){
context = this.context
context = this.context;
}
}
let promise = data_preferences.getPreferences(context, 'mystore');
promise.then((pref) => {
preferences = pref;
}).catch((err) => {
console.info("Failed to get preferences.");
})
```
3. 存入数据。
......@@ -119,16 +133,12 @@
使用put方法保存数据到缓存的实例中。
```js
promise.then((preferences) => {
let putPromise = preferences.put('startup', 'auto');
putPromise.then(() => {
console.info("Succeeded in putting the value of 'startup'.");
}).catch((err) => {
console.info("Failed to put the value of 'startup'. Cause: " + err);
})
}).catch((err) => {
console.info("Failed to get preferences.");
})
```
4. 读取数据。
......@@ -136,16 +146,12 @@
使用get方法读取数据。
```js
promise.then((preferences) => {
let getPromise = preferences.get('startup', 'default');
getPromise.then((value) => {
console.info("The value of 'startup' is " + value);
}).catch((err) => {
console.info("Failed to get the value of 'startup'. Cause: " + err);
})
}).catch((err) => {
console.info("Failed to get preferences.")
});
```
5. 数据持久化。
......@@ -165,7 +171,7 @@
console.info("The key" + key + " changed.");
}
preferences.on('change', observer);
// 数据产生变更,由'auto'变为'manual'
// 数据产生变更,由'auto'变为'manual'
preferences.put('startup', 'manual', function (err) {
if (err) {
console.info("Failed to put the value of 'startup'. Cause: " + err);
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册