【问题标题】:Angular Observable not updating when I subscribe.当我订阅时,Angular Observable 没有更新。
【发布时间】:2018-03-31 15:49:27
【问题描述】:

我的主要目标是拥有一个拥有地图并返回可观察对象的服务。我想拦截该 observable 的更新并将数据转换为我在 UI 中显示的字符串。我在其他地方做这种事情,但它似乎不喜欢使用地图,我不确定发生了什么。 该服务类似于:

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
        });
    }
}

不太确定去哪里。我一直在用数组做这种事情 东西|异步 技术,但我卡住了。

【问题讨论】:

    标签: angular observable


    【解决方案1】:

    您需要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();
        }
    }
    

    【讨论】:

      【解决方案2】:

      我认为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$;
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-01-20
        • 2017-03-24
        • 2018-09-08
        • 2017-10-18
        • 1970-01-01
        • 2018-01-24
        • 1970-01-01
        相关资源
        最近更新 更多