2016-08-13 100 views
3

我有一個數據服務,通過HTTP運行查詢(由某個組件觸發),然後通過Observable公開結果。其他組件將訂閱Observable並更新他們對結果的看法。RxJS/Angular2:爲什麼我的主題訂閱者未被調用?

無論如何,這是主意,但它不工作。這是我的代碼。

ItemListDataService:

import { Injectable } from '@angular/core'; 
import { Http, Response } from '@angular/http'; 
import { Observable, Subject } from "rxjs"; 
import 'rxjs/add/operator/map'; 

@Injectable() 
export class ItemListDataService { 
    private issues$: Subject<any>; 

    constructor(private http: Http) { 
    this.issues$ = new Subject(); 
    this.issues$.subscribe(x => console.log('GOT IT', x)); 
    } 

    getList(): Observable<any> { 
    return this.issues$; 
    } 

    refresh() { 
    this.http.get('/whatever') 
     .map((response: Response) => response.json()) 
     .subscribe(data => this.issues$.next(data)); 
    } 
} 

ItemListComponent:

import { Component } from '@angular/core'; 
import { Observable } from 'rxjs'; 

import { ItemListDataService } from './item-list-data-service'; 
@Component({ 
    selector: 'app-item-list', 
    templateUrl: './item-list.component.html', 
    styleUrls: ['./item-list.component.css'], 
    providers: [ItemListDataService] 
}) 
export class ItemListComponent { 
    data: any; 

    constructor(itemListDataService: ItemListDataService) { 
    itemListDataService.getList().subscribe(data => { 
     console.log('DATA CHANGED'); 
     this.data = data; 
    }, err => { 
     console.log('ERR', err) 
    },() => { 
     console.log('DONE'); 
    }); 
    } 
} 

ItemListDataService.constructor創建的用戶被調用每次refresh()被調用時。唯一不起作用的是組件中的訂閱 - 既沒有在那裏調用回調。

我在做什麼錯?

+0

Woo調用refresh()?它從哪裏得到ItemListDataService?您已將ItemListDataService添加到ItemListComponent的提供者,以便組件(及其子組件)將獲得自己的服務實例,與其他組件不同。 –

+0

@JBNizet謝謝,經過一番研究,我得出了同樣的結論。事實上,問題是每個組件都有自己的服務實例。來自Angular 1(和許多其他的DI框架),我期待他們是單身人士。活到老,學到老。 :-) 隨意張貼,作爲答案。 –

回答

9

正如JB Nizet在評論中指出的那樣,原因在於該服務不是單例,即每個用戶都有一個新實例。與角1相反,在A2服務不是單身人士。

爲了讓多個服務/組件共享服務的一個實例,請將其置於父@Component或@NgModule的提供者中。

+0

如何確保服務在根組件中不是多次實例化的?我的意思是(在離子中使用ng2)我的組件不具有ngmodule。我假定在根組件ngmodule中定義的服務是單例,但我剛剛確認他們有每個組件的實例。 –

+0

我對離子不是很熟悉,我可以提供的最好的方式是使用「離子服務單身人士」的谷歌搜索。以下是最重要的結果之一 - 可能適用於您:https://forum.ionicframework.com/t/how-to-create-a-singleton-service/40113/2 –