【发布时间】:2020-11-18 15:34:24
【问题描述】:
我有两个服务和一个组件。组件侦听服务 B 的服务 A。我目前正在服务 A 中订阅服务 B,运行过滤功能,然后过滤功能正在触发组件侦听的服务 A 中的 observable。最佳做法是不从服务 A 订阅服务 B,而是将该可观察对象传递给将成为唯一侦听器的组件,但我不知道如何正确处理它。
当前设置:
当用户更改类型时,服务 B 中的订阅会触发服务 A 侦听的订阅,然后获取该数据并创建一个新数组并触发组件侦听的 productsChanged 主题
Service A {
productsChanged = new BehaviorSubject<Product[]>([]);
types$: Subscription;
private json: Product[] = ProductsJSON;
private currentProducts: Product[] = [];
constructor(private typeService: TypeService) {
this.types$ = this.typeService.typeChanged.subscribe((type: Type) => {
this.filterProducts(type);
});
}
filterProducts(type: Type): void {
this.currentProducts = [];
// Do Some Filtering to Set the Current Products Based on Given Type
}
}
当用户更改产品类型时,它会触发“TypeChanged”,主题 A 会监听以过滤掉与类型不匹配的产品
Service B {
typeChanged = new BehaviorSubject<Type>(Defaults.TYPE);
private chosenType: Type;
constructor() {
this.typeChanged.pipe(take(1)).subscribe((type) => {
this.chosenType = type;
});
}
setType(type: Type): void {
this.chosenType = type;
this.typeChanged.next(this.chosenType);
}
}
组件在 HTML 中订阅,只是输出一个产品列表
Component {
products$: Observable<any>;
constructor(private productService: ProductService) {
this.products$ = this.productService.productsChanged.pipe(
map((product) => {
return product;
}),
);
}
}
【问题讨论】:
标签: angular rxjs observable subscription behaviorsubject