2017-10-19 58 views
0

我的主要目標是擁有一個擁有一張地圖並返回一個觀察值的服務。我想攔截該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 
     }); 
    } 
} 

不是真的知道該去哪裏。我總是用陣列來做這類事情,異步 技術,但我卡住了。

回答

0

我認爲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$; 
    } 
} 
0

你需要一個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(); 
    } 
}