2017-10-19 2 views
0

내 주요 목표는지도를 소유하고 관찰 가능을 반환하는 서비스를 갖는 것입니다. 해당 관찰 가능 업데이트를 가로 채서 UI에 표시되는 문자열로 변환하고 싶습니다. 나는 다른 곳에서 이런 종류의 일을하지만지도로 작업하는 것을 좋아하지 않는다. 정확히 무슨 일이 일어나고 있는지 확신 할 수 없다. 서비스는 유사합니다각도 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); 
    } 
} 

그리고 내 구성 요소에 나는 몇 가지를 시도했지만 내가 원하는 것을 달성 할 수없는 것.

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

정말 확실하지 갈 : 내 목표는지도에 업데이트를 받아 문자열로 변환하고 내가 좋아하는 뭔가를 시도 그래서 내 UI를 업데이트하는 것입니다. 나는 항상 배열과 함께 이런 일을한다. something | 비동기 기술이지만 붙어 있습니다.

답변

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

당신은 Observable에 물건을 보낼 Subject이 필요합니다. 좋아요 :

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(); 
    } 
} 
관련 문제