我订阅时Angular Observable不会更新。

时间:2017-10-19 14:50:00

标签: angular observable

我的主要目标是拥有一个拥有地图的服务并返回一个可观察的服务。我想截取该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
        });
    }
}

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

您需要SubjectObservable发送内容。像这样:

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