我无法理解 observable 和 observer (rxjs),我知道 observable 可以将消息发送给观察者,而观察者订阅 observable,但我不知道如何设置它?
假设我想请求 URL,第一次用户调用“loadData”时,数据从 http 请求加载,并保存在类中本地,下次用户调用“loadData”时,我们不想加载来自http,但在本地获取数据,但我想使用相同的代码“loadData”,它应该返回Observer,所以开发人员不知道数据加载到哪里以及如何加载!
let data = [];
function loadData():Observer {
var observer = new Observer();
if (data.length > 0) {
var observable = new Observable.from(data);
observable.add(observer);
observable.notify();
} else {
var observable = this.http.get("data.json");
observable.add(observer);
observable.readyData( (data) => {
this.data = data;
observable.notify();
};
}
}
var observer = loadData();
observer.dataComing((data) => console.log(data));
任何解释或指向任何页面的链接都会很棒,我了解 Array 等中的 map filter reduce,以及简单的观察者模式,但不是 RXJS 方式,这非常令人困惑!
非常感谢!
最佳答案
这是观察者/可观察的样本:
var obs = Observable.create((observer) => {
setTimeout(() => {
observer.next('some event');
}, 1000);
});
obs.subscribe((event) => {
// The event is received here
});
观察者用于触发一个事件,而observable简而言之就是接收事件。大多数时候,观察者是间隔使用的。例如通过 Angular2 的 HTTP 支持
这里有一些关于响应式编程的链接:
- http://slides.com/robwormald/everything-is-a-stream
- https://gist.github.com/staltz/868e7e9bc2a7b8c1f754
对于您的特定用例,您可以使用这个:
loadData(url:string):Observable {
if (this.cachedData) {
return Observable.of(this.cachedData);
} else {
return this.get(...).map(res => res.map()).do((data) => {
this.cachedData = data;
});
}
}
编辑
我会这样重构你的代码:
@Injectable()
export class LoungesService {
constructor(private http:Http) {
this.loungesByCity = {};
}
getLoungesByCity(city:City):Observable<any> {
if (this.loungesByCity && this.loungesByCity[city.id]) {
return Observable.of(this. loungesByCity[city.id]);
} else {
return this.http.get("lounges.json")
.map(res => <Lounge[]> res.json().data)
.map((lounges) => {
return lounges.filter((lounge) => lounge.city_id === city.id);
})
.do(data => this.loungesByCity[city.id] = data);
}
}
请注意,在引导您的应用程序时,必须将 LoungesService 定义为共享服务:
bootstrap(AppComponent, [ LoungesService ]);
关于javascript - rxjs - 理解 observable 和 observer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36103347/