当我订阅时,Angular Observable 没有更新。

标签 angular observable

我的主要目标是拥有一个拥有 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/

相关文章:

rxjs - 组合 2 个 Observables rxjs

java - DeferredResult 导致 Weblogic 中的异常

angular - Rxjs - 检查 Observable 是否为空,而不订阅它

Angular 5 应用程序未注册服务 worker

javascript - Angular2 RC5导入第3方JS库: Showdown

javascript - 如果仅返回一个对象,则 API 调用不适用于 TypeScript

css - Angular2 部署 - 如何自动修改 index.html 中对 styles.bundle.css 的引用

angular - 如何防止 Angular ngFor 将数据追加到当前列表?

angular - 取消订阅服务内部的 Observables?

angular - rxjs: - 接收订阅前发出的值