我的主要目标是拥有一个拥有 map 并返回可观察值的服务。我想拦截该可观察的更新并将数据转换为我在 UI 中显示的字符串。我在其他地方做过类似的事情,但它似乎不喜欢使用 map ,我不太确定发生了什么。 该服务类似于:
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);
}
}
然后在我的组件中我尝试了几件事,但似乎无法完成我想要的。我的目标是对 map 进行任何更新并将它们转换为字符串并更新我的用户界面所以我尝试了类似的操作:
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
不是正确的选择。它将发出一次 map ,然后发出完整事件。我建议使用 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$;
}
}
关于当我订阅时,Angular Observable 没有更新。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46832737/