【发布时间】:2021-08-07 02:56:23
【问题描述】:
我正在使用角度行为主题来发出两个子组件之间的值。这些组件是无限页面(父组件)滚动的一部分。我的问题是,在单击行为主题中多次调用 ngoni,所以我尝试了多种方法来解决这个问题,但我不能。以下是我的代码:
发射器服务:
export class emitDataService {
private productColorUpdate = new BehaviorSubject<any>(null);
private productVariantUpate = new BehaviorSubject<any>(null);
getCurrentProductColor = this.productColorUpdate.asObservable();
getProductVariantUpdate = this.productVariantUpate.asObservable();
emitValue(value: string, values: string) {
this.productColorUpdate.next({ value, values });
}
emitVariantValue(prod: string, prodcode: string, prodcolor: string) {
this.productVariantUpate.next({ prodvariant, prodcode, prodcolor });
}
}
组件 1:
ngOnInit(): void {
this.sub = this.emitDataService.getCurrentProductColor
.subscribe((data) => {
if (data) {
this.someMethod(data);
}
});
}
someMethod():void {
}
clicks(data):void{
//mylogic goes here at the end of the statement i trigger the emit
this.customDataService.emitVariantValue(prodcode, prodvalue, prodcolor);
}
组件 2:
ngOnInit(): void {
this.sub = this.emitDataService.emitVariantValue.subscribe((data) => {
if (data) {
this.somePrivateMethod(data);
}
});
}
somePrivateMethod() : void{
}
triggerEmits():void {
this.customDataService.emitValue(prodcolor, prodcode);
}
如果我在 ng onit 或 ngchanges 中使用取消订阅,它不会在第一次点击时触发,如下所示:
ngOnInit(): void {
this.sub = this.emitDataService.getCurrentProductColor
.subscribe((data) => {
if (data) {
this.someMethod(data);
}
}).unsubscribe();
}
由于父组件使用了ngdestroy所以它没有调用这个页面ngdestroy。请帮我解决这个问题,以避免在 ngoni 中多次调用
【问题讨论】:
-
如果数据只是从子节点移动到父节点,则不需要服务。阅读组件输出。它们定义为 EventEmitter,它是 rxjs 主题的扩展。从子组件发出点击,在父组件中所有事件触发相同的方法。
-
@diclo- 你能举一些例子或分享一些链接
-
显示子组件的 html 代码是什么?我认为这与 Angular 中的变更检测有关。
标签: angular rxjs angular9 angular2-observables