RxJS/Angular2:为什么我的主题订阅者没有被调用?

Kon*_*rus 3 rxjs angular

我有一个数据服务,它通过HTTP运行查询(由某个组件触发),然后通过公开结果Observable.其他组件将订阅该组件Observable并更新其结果视图.

无论如何,这是个主意,但它不起作用.这是我的代码.

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));
  }
}
Run Code Online (Sandbox Code Playgroud)

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');
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

ItemListDataService.constructor每次调用时都会调用创建的订户refresh().唯一不起作用的是组件中的订阅 - 在那里都没有调用回调.

我究竟做错了什么?

Kon*_*rus 9

正如JB Nizet在评论中指出的那样,原因是该服务不是单例,即每个订阅者都获得了一个新实例.与Angular 1相反,A2服务不是单身人士.

为了让多个服务/组件共享一个服务实例,将其放在父@Component或@NgModule的提供者中.