为使用方便简单二次封装了一下getStringByName方法,用于向资源库读取stirng.json对应name的value值,但是有点小问题。这是个异步方法,有时(有的场景)页面代码跑的快,数据还没更新过来,导致显示内容是空的,如何二次封装为同步方法?或其它封装、调用技巧?
封装代码:
// StringByName.ets
import { BusinessError } from '@ohos.base';
import { common } from '@kit.AbilityKit';
class StringByName {
context = getContext(this) as common.UIAbilityContext
async stringByName(name: string): Promise<string> {
return new Promise((resolve, reject) => {
this.context.resourceManager.getStringByName(name, (error: BusinessError | null, value: string) => {
if (error) {
reject(error); // 使用reject来拒绝Promise
} else {
resolve(value); //使用resolve来解决Promise
}
});
});
}
}
export default new StringByName();
//调用代码:
import StringByName from '../../StringByName';
@State Pull_to_load_more: string = ''
@State Release_to_load: string = ''
@State Happily_loading: string = ''
StringByName.stringByName('Pull_to_load_more').then(str => {
this.Pull_to_load_more = str
})
StringByName.stringByName('Release_to_load').then(str => {
this.Release_to_load = str
})
StringByName.stringByName('Happily_loading').then(str => {
this.Happily_loading = str
})
// refreshConfigurator属性设置
setTimeout(() => {//setTimeout()临时方案,目的是等待数据后再传给目标接口
this.refreshConfigurator.setLoadTextPullUp1(this.Pull_to_load_more) //'正在上拉刷新...'
this.refreshConfigurator.setLoadTextPullUp2(this.Release_to_load) //'放开刷新'
this.refreshConfigurator.setLoadTextLoading(this.Happily_loading) //'正在玩命加载中...'
}, 100)
可以使用getStringByNameSync同步获取资源名称,参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-resource-manager-V5\#getstringbynamesync9