如何更新 Angular Observable 的订阅者

How to update subscribers of Angular Observable

在我的 angular 应用程序中,我创建了一个 Observable 来为多个组件提供数据更新。当用户点击一个按钮时,Observable 的所有订阅者都应该使用不同的数据集进行更新。下面是代码。

import { Observable } from 'rxjs/Observable';
import { Subscriber } from 'rxjs/Subscriber';

export class MyService {
private data: number[] = [5,6,7,8];

/// The observable given to outside
private observable: Observable<number[]>;

/// Subscribers of the observable which is given to outside
private subscribers: Map<number, Subscriber<number[]>>;
private nextSubscriberId = 0;

constructor() {
    this.subscribers = new Map();
    this.observable = new Observable(subscriber => {
        const id = ++this.nextSubscriberId;
        this.subscribers.set(id, subscriber);

        subscriber.next(data);

        return () => { this.subscribers.delete(id); };
    });

}

}

在按钮单击事件中,我执行以下操作

data = [1,2,3,4]; 
this.subscribers.forEach((subscriber, key) => {
    subscriber.next(data);
    });

我的问题是, 这是管理 Observable 订阅者的最佳方式吗?有没有其他方法可以处理订户而不是由我们自己管理它们?

您基本上是在尝试创建您自己的 Subject 实现。试试这个:

import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';

export class MyService {
  private source = new Subject<number[]>();
  data$ = this.source.asObservable();

  constructor() {}

  next(data: number[]) {
    this.source.next(data);
  }
}

producer.component.ts

class ProducerComponent {
  constructor(private myService: MyService) {}

  ngOnInit() {
    this.myService.next([1,2,3]);
  }
}

consumer.component.ts

class ConsumerComponent {
  constructor(private myService: MyService) {}

  ngOnInit() {
    this.myService.data$.subscribe(data => // ...)
  }
}

如果你想在你的服务中有一个初始值,替换:

private source = new Subject<number[]>();

private source = new BehaviorSubject<number[]>([1,2,3,4]);,其中[1,2,3,4]为初始值。