2016-08-13 97 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 –