我在本地存储中保存页面的设置。效果很好。
const settings = [amount, hours]
localStorage.setItem('settings', JSON.stringify(settings));现在,同一个服务类应该只返回amount。当然,这也是一个承诺。很好,但是我想首先分解amount和hours的数据集,只返回amount。类似这样的东西:(当然,这不会起作用,因为这个函数是在异步数据获取过程中完成的)。
public getAmount(){
this.storage.get('settings').then((settings) => {
console.log('SettingsService: settings=' + settings[0]);
this.amount= settings[0];
});
return this.amount;
}无论如何,什么是最好的实践或模式来处理这样的数据分解?
amount。如果我想到从不同来源收集数据的EAI模式内容,要想组成一个更智能的返回值,还需要在所有部分数据到达之前阻止它。那么,我们如何阻止JavasScript中的数据获取?
谢谢你分享你的想法。
发布于 2019-04-18 18:58:52
我至少看到了两件事: 1)为什么要将数据保存在数组中:[amount, hours]?最好创建一个模型接口,并将其存储在对象(而不是数组)中:
export interface Settings {
amount: Amount; // or maybe number - choice is yours?
hours: number;
}2)一旦你有了模型,它就会非常直接。你应该使用可观察的而不是承诺。一旦您有了可观察到的--很容易将设置映射到数量:
import { from } from 'rxjs';
var observableFromPromise = from(promiseSrc);
public getAmount(): Observable<Amount> {
from(this.storage.get('settings')).pipe(
map((settings: Settings) => settings.amount)
);
}然后,您将能够在模板或其他组件/服务中使用“金额”值。
// create observable field in component.ts
public amount$: Observable<Amount> = service.getAmount();
// use in component.html
<p>{{amount$ | async}}</p>
// or use in component.ts
this.amount$.subscribe(amount => console.log('this is the amount:', amount));https://stackoverflow.com/questions/55752112
复制相似问题