【问题标题】:How to update subscribers of Angular Observable如何更新 Angular Observable 的订阅者
【发布时间】:2018-09-08 17:15:10
【问题描述】:

在我的 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 订阅者的最佳方式吗?有没有其他方法来处理订阅者而不是我们自己管理它们?

【问题讨论】:

    标签: angular observer-pattern angular-observable


    【解决方案1】:

    您基本上是在尝试创建自己的 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&lt;number[]&gt;();

    private source = new BehaviorSubject&lt;number[]&gt;([1,2,3,4]);,其中[1,2,3,4] 是初始值。

    【讨论】:

    • 感谢您的及时回复,我试试这个。但是有没有办法在有人订阅/取消订阅我的 Observable 时收到通知?
    • 如果我解决了你的问题,请考虑接受我的回答:)
    • 假设我通过 Observable 发送的数据是从外部服务接收的。如果有人订阅了我的 Observable,那么我可以从该外部服务请求数据,当有人取消订阅时,同样的方式,如果没有更多订阅者,那么我可以从该外部服务取消注册.. 我该怎么做这个提议的解决方案?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 2018-03-31
    • 1970-01-01
    • 2017-01-30
    • 1970-01-01
    • 2019-08-16
    • 2018-01-24
    相关资源
    最近更新 更多