2017-09-28 73 views
0

我有一個Angular 2/4服務,它使用observables與其他組件進行通信。角度服務沒有更新訂閱組件

服務:

let EVENTS = [ 
    { 
     event: 'foo', 
     timestamp: 1512205360 
    }, 
    { 
     event: 'bar', 
     timestamp: 1511208360 
    } 
    ]; 

@Injectable() 
export class EventsService { 

    subject = new BehaviorSubject<any>(EVENTS); 

    getEvents(): Observable<any> { 
    return this.subject.asObservable(); 
    } 

    deleteEvent(deletedEvent) { 
    EVENTS = EVENTS.filter((event) => event.timestamp != deletedEvent.timestamp); 
    this.subject.next(EVENTS); 
    } 

    search(searchTerm) { 
    const newEvents = EVENTS.filter((obj) => obj.event.includes(searchTerm)); 
    this.subject.next(newEvents); 
    } 
} 

home組成部分能夠在申請開通此項服務並正確當事件被刪除更新:

export class HomeComponent { 

    events; 
    subscription: Subscription; 

    constructor(private eventsService: EventsService) { 
    this.subscription = this.eventsService.getEvents().subscribe(events => this.events = events); 
    } 

    deleteEvent = (event) => { 
    this.eventsService.deleteEvent(event); 
    } 
} 

我也有顯示根組件搜索表單。表單提交後,它會調用服務,執行搜索並調用this.subject.next,結果如上所示。但是,這些結果並未反映在home組件中。我哪裏錯了?完整代碼請參見plnkr.co/edit/V5AndArFWy7erX2WIL7N

回答

1

如果您多次提供服務,您將獲得多個實例,但這不適用於通信,因爲發件人和收件人未使用同一實例。

要爲整個應用程序獲取單個實例,請在AppModule以及其他地方提供服務。

Plunker example