首页 > 解决方案 > 如何避免重复订阅 Angular?

问题描述

有一个地方发出事件:

private action: Subject<IActionData> = new Subject();

 apply(data?: IActionData) {
    this.action.next(data);
 }

我有<app-word-block>监听事件的组件:

this.listener.changes().subscribe((res: IActionData) => {
   // Show type here
});

问题是我在页面上重用这个组件,例如:

<app-word-block type="1"></app-word-block>
<app-word-block type="2"></app-word-block>
<app-word-block type="3"></app-word-block>

因此事件监听器工作了三遍。

如何避免休息并只听一个事件?

标签: angularangular8

解决方案


编辑: 评论后,我误解了你的问题。我之前的回答解决了这个“当我在我的应用程序中导航时我的订阅是重复的”,如果您对此感兴趣,请在下面查看。我可以提出一些解决方案:

  • 您可以在“父组件”中进行订阅并在输入指令中传递数据
  • 使用服务并在那里进行订阅并在您的组件中检索它。

稍后我会尝试给你一些例子。

编辑2: 如您的帖子评论中所述。如果您在同一个模板中多次使用某个组件,则不应订阅该组件中的主题。

父订阅方式:在父组件中进行订阅。我们没有您的代码,所以我假设您需要向您的组件发送一些数据,我将通过一个粗略的示例向您展示。父组件:

ts:

import { Component, OnInit } from "@angular/core";
import { BehaviorSubject } from "rxjs";

@Component({
    selector: "app-parent",
    templateUrl: "./parent.component.html",
    styleUrls: ["./parent.component.scss"]
})
export class ParentComponent implements OnInit {
    private sub;
    private i = 0;
    private subject = new BehaviorSubject<any>(0);
    constructor() {}

    ngOnInit() {
        this.sub = this.subject.subscribe(data => {
            this.i = data;
        });
    }
    click() {
        this.i++;
        this.subject.next(this.i);
    }
    ngOnDestroy() {
        if (this.sub) {
            this.sub.unsubscribe();
        }
    }
}

html:

<app-child  [value]="i" ></app-child>
<app-child [value]="i" ></app-child>
<app-child  [value]="i"></app-child>
<app-child [value]="i" ></app-child>
<!-- button for testing if it works -->
<button (click)="click()">test</button>

子组件:ts:

import { Component, OnInit, Input } from "@angular/core";

@Component({
    selector: "app-child",
    templateUrl: "./child.component.html",
    styleUrls: ["./child.component.scss"]
})
export class ChildComponent implements OnInit {
    @Input() value;

    constructor() {}

    ngOnInit() {}
}

最后用 html 检查值是否通过和同步。

<p>
  {{this.value}}
</p>

以前的答案:

订阅需要取消订阅,否则您将有多个订阅,如您所述。你的组件需要实现(onDestroy)

   export class YourComponent implements OnInit,OnDestroy

你需要导入它

import { Component, OnInit,OnDestroy } from '@angular/core';

您必须在 var 中设置您的订阅以便稍后对其进行操作。

    this.sub = this.listener.changes().subscribe((res: IActionData) => {
   // Show type here
});

然后在您的组件中,您将需要一个函数 ngOnDestroy();

ngOnDestroy() {
    if (this.sub) { // check if it's defined sometimes you can get some trouble there,
      this.sub.unsubsribe();
    } 
}

您应该注意生命周期 Angular,它是 Angular 的一个重要特征。


推荐阅读