当我订阅时,Angular Observable不会更新。
问题描述:
我的主要目标是拥有一个拥有一张地图并返回一个观察值的服务。我想拦截该observable的更新并将数据转换为我在UI中显示的字符串。我在其他地方做这种事情,但似乎不喜欢使用地图,我不确定发生了什么。 该服务类似于:当我订阅时,Angular Observable不会更新。
MyService {
myMap: {[index:string]: string};
add(key:string, value:string) {
this.map[key] = value;
}
remove(key:string) {
delete this.map[key];
}
getMap() Observable<{[index:string]: string}> {
return Observable.of(this.map);
}
}
然后在我的部分我已经试过几件事情,但似乎无法做到我想要的东西。我的目标是采取任何更新地图,并将其转换为字符串并更新我的UI所以我想是这样:
MyComponent {
constructor(private myService: MyService) {
}
ngOnInit() {
this.myService.getMap().subscribe((update) => {
// I would think I would consistently get updated here but this
// only hits once. At this point update would be the map and I
// would process the data into the string I want to display in the
// UI
});
}
}
不是真的知道该去哪里。我总是用阵列来做这类事情,异步 技术,但我卡住了。
答
我认为Observable.of
是不是要走的路。它会发射地图一次,然后发出完整的事件。我会建议使用BehaviorSubject
代替,并保持同步手动:
MyService {
myMap: {[index:string]: string};
myMap$ = new BehaviorSubject<{[index:string]: string}>(this.myMap);
add(key:string, value:string) {
this.map[key] = value;
this.myMap$.next(this.map);
}
remove(key:string) {
delete this.map[key];
this.myMap$.next(this.map);
}
getMap() Observable<{[index:string]: string}> {
return this.myMap$;
}
}
答
你需要一个Subject
送东西给Observable
。像这样:
MyService {
mapSource = new Subject()<{[index:string]: string}>();
myMap: {[index:string]: string};
add(key:string, value:string) {
this.map[key] = value;
this.mapSource.next(this.map);
}
remove(key:string) {
delete this.map[key];
this.mapSource.next(this.map);
}
getMap() Observable<{[index:string]: string}> {
return this.mapSource.asObservable();
}
}