我使用Ionic 2开发了一个使用Angular 2的应用程序。
我想以两种方式更新我的组件列表。
当用户离开页面时取消自动刷新并在他返回时重新初始化。我不想在用户进入页面时立即更新,但仅在上次更新后30分钟完成时才更新。
实现这一目标的最佳方法是什么?我想知道更新是否会发生冲突,如果是,如何取消所有更新并仅进行最后一次通话?
我是Angular 2的新手,我对Observables有些困惑。这就是我所拥有的:
import { Component } from '@angular/core';
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/share';
import 'rxjs/add/operator/mergeMap';
import "rxjs/add/observable/interval";
import { NavController } from 'ionic-angular';
import { EventData } from '../../providers/event-data';
@Component({
selector: 'page-event-list',
templateUrl: 'event-list.html'
})
export class EventListPage {
public events = [];
private subscription;
constructor(public navCtrl: NavController, public eventData: EventData) {}
ionViewDidEnter() {
this.load();
}
ionViewDidLeave() {
this.cancel();
}
load() {
let observable = Observable
.interval(10000)
.flatMap(() => {
return this.eventData.load();
})
.share();
this.subscription = observable
.subscribe(events => this.events = events, error => console.log(error));
return observable;
}
reload(refresher) {
this.load()
.subscribe(null, null, () => refresher.complete());
}
cancel() {
if (this.subscription.closed) {
return;
}
this.subscription.unsubscribe();
}
}
答案 0 :(得分:0)
您可以使用以下内容解决此问题:
// this can be a click-event, or anything else, in this case it'll just be a simple manualTrigger$.next();
let manualTrigger$ = new Rx.Subject();
// the timer will trigger immediately and then every 30seconds
let intervalTrigger$ = new Rx.Observable.timer(0, 30000);
// this is our actual combination "logic", a simple "switchMapTo"
// switchMap switches to a new subscription of our timer each time manualTrigger$ triggers and discards the old one
let resetIntervalWhenTriggeredManually$ = manualTrigger$
.switchMapTo(intervalTrigger$);
// make sure to unsubscribe when the view is destroyed or just use the async-pipe in your template!
resetIntervalWhenTriggeredManually$
.flatMap(makeRestCall); // here you insert your rest-call
.subscribe(
data => console.log("Data is:", data),
error => console.error("Error: " + error)
);
您也可以在此处查看此jsbin以获取正在运行的示例:http://jsbin.com/titujecuba/edit?js,console
当用户离开/进入页面时,您想要自动停止/继续更新的部分无法使用纯rxjs完成,您必须在上次更新的某个位置保留日期并检查是否为小时段:< / p>
// check every second
const thirtyMinutes: number = 1000 * 60 * 30;
let lastUpdated: number = -1;
let intervalTrigger$ = new Rx.Observable.timer(0, 1000);
let resetIntervalWhenTriggeredManually$ = manualTrigger$
.do(() => lastUpdated = -1) // rest the last update to force an update
.switchMapTo(intervalTrigger$)
.filter(() => return +new Date() - lastUpdated >= thirtyMinutes) // only propagate dispatches if time elapsed is 30minutes
.do(() => lastUpdate = +new Date());
resetIntervalWhenTriggeredManually$
.flatMap(makeRestCall); // here you insert your rest-call
.subscribe(
data => console.log("Data is:", data),
error => console.error("Error: " + error)
);
你必须把它放在一个服务中,否则如果视图被破坏,状态就会丢失。