在我的角度应用中,我创建了一个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订户的最佳方式吗?是否有其他方式来处理订阅者而不是由我们自己管理?
答案 0 :(得分:3)
你基本上想要创建自己的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]
是初始值。