【问题标题】:Angular Behavior Subject called mulitple times in infinite scrollAngular Behaviorsubject 在无限滚动中被多次调用
【发布时间】: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


【解决方案1】:

在单击行为主题中多次调用 ngoni

事件未触发ngOnInit()。您正在订阅在这个无限滚动器中呈现的这些组件中的可观察服务。在您取消订阅之前,RxJS 订阅将保持活动状态。

因此,当每个组件被实例化时,它们都会订阅您的服务 observable。当你点击一个组件发出一个新的 Subject 值时,所有订阅它的 observable 的组件都会收到这个新值。

您的unsubscribe() 代码示例不起作用的原因是它正在订阅,然后立即取消订阅。

如果您的要求是让每对单独的 Component 1Component 2 相互通信,您可能需要将它们封装在父组件中。此父组件的逻辑将与您的服务相同。但是,不是让所有组件都订阅服务,而是让每对 Component 1Component 2 订阅它们各自的父组件。

【讨论】:

    猜你喜欢
    • 2019-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 2019-08-07
    相关资源
    最近更新 更多