【问题标题】:RxJS / Angular2: Why is my subject subscriber not invoked?RxJS / Angular2:为什么我的主题订阅者没有被调用?
【发布时间】:2016-08-13 16:01:18
【问题描述】:

我有一个数据服务,它通过 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));
  }
}

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

每次调用refresh() 时都会调用在ItemListDataService.constructor 中创建的订阅者。唯一不起作用的是组件中的订阅 - 那里从未调用任何回调。

我做错了什么?

【问题讨论】:

  • Woo 调用 refresh()?它从哪里获得 ItemListDataService?您已将 ItemListDataService 添加到 ItemListComponent 的提供者中,因此该组件(及其子组件)将获得自己的服务实例,与其他组件不同。
  • @JBNizet 谢谢,经过一些研究,我得出了同样的结论。事实上,问题在于每个组件都有自己的服务实例。来自 Angular 1(和许多其他 DI 框架),我期待它们是单例的。活到老,学到老。 :-) 随意张贴作为答案。

标签: angular rxjs


【解决方案1】:

正如 JB Nizet 在评论中指出的那样,原因是该服务不是单例的,即每个订阅者都有一个新实例。与 Angular 1 不同,A2 中的服务不是单例的。

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

【讨论】:

  • 如何确保服务不会在根组件中多次实例化?我的意思是(在 ionic 中使用 ng2)我的组件没有 ngmodule。我假设根组件 ngmodule 中定义的服务是单例的,但我刚刚确认它们对每个组件都有实例。
  • 我对 ionic 不是很熟悉,我能提供的最好的方法就是在谷歌上搜索“ionic service singleton”。这是最佳结果之一 - 可能对您有用:forum.ionicframework.com/t/how-to-create-a-singleton-service/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-18
  • 2018-03-10
  • 1970-01-01
相关资源
最近更新 更多