【发布时间】:2017-11-01 00:22:12
【问题描述】:
我在确定我开始构建的服务的顺序时遇到了很多麻烦。我想做的是从基于 Promise 的存储提供程序加载缓存,然后使用该缓存启动一个 observable。 HTTP 请求解决后,我想用新的响应替换旧的缓存。
我很难弄清楚这个过程,希望能得到任何帮助。
伪码
import {Injectable} from "@angular/core";
import {Http} from "@angular/http";
import rxjs/add/operators/map;
import rxjs/add/operators/startWith;
import {Storage} from "@ionic/storage";
@Injectable()
export class DataService {
private _cache = {};
constructor(public http: Http; public storage: Storage){}
public getCache(): Promise<any> {
return this.storage.get('storageKey');
}
public setCache(val: any): Promise<any> {
return this.storage.set('storageKey', val);
}
public getData(): Observable<any> {
// Step 1: Get cache.
this.getCache().then(cache => this._cache = cache);
// Step 2: Make HTTP request.
return this.http.get('endpoint')
// Step 3: Set data mapping
.map(res => this.normalize(res))
// Step 4: Use resolved cache as startWith value
.startWith(this._cache)
// Step 5: Set cache to response body.
.do(result => this.setCache(result).then(() => console.log('I resolved'));
}
private normalize(data: Response): any {
// Fun data-mapping stuff here
}
}
此代码旨在在移动设备上运行,其中速度错觉以及离线功能是第一要务。通过最初使用旧缓存设置视图,用户可以查看已存储的内容,如果 HTTP 请求失败(网络慢,或没有网络),没什么大不了的,我们回退到缓存。但是,如果用户在线,我们应该利用这个机会将旧缓存替换为来自 HTTP 请求的新响应。
感谢您的任何帮助,如果我需要进一步说明,请告诉我。
【问题讨论】:
-
这里的类型没有意义。既然你
startWith(cache),那么cache必须与你的结果JSON 承诺流的类型相同。但是,它也会缓存 resolved JSON 对象,除非cache和res.json()都是Promise<Promise<...,否则这是不可能的。 -
我有一个映射函数,而不是
.map(res => res.json()。让我更新一下。
标签: angular ionic-framework rxjs ionic3