簡體   English   中英

Angular 主題和訂閱

[英]Angular Subject and Subscription

當單擊按鈕時,我有一個具有方法 interval() 的組件。

 interval() {
    this.statusInterval = interval(2000).subscribe(x => {
      this.interval2 = x;
      console.log(this.interval2);
      this.assetItemActionService.sendNumber(x);
    })
  }

在構造函數中,我有這個訂閱,它應該更新那個值。

 interval2 = 0;
 percentSubscription= Subscription;
  constructor(private service:Service) {
    console.log('takeee');
    this.percentSubscription = this.service.number$.subscribe(percent => {
      console.log("set number");
      this.interval2 = percent;
    }, error => console.log(error))
  }

上面的 2 個代碼片段在同一個組件中。

在服務中,我有這個主題不斷更新。

private number: Subject<number> = new Subject();
number$ = this.number.asObservable();

  sendNumber(number) {
    console.log('received');
    this.number.next(number);
  }

問題是當我路由到另一個頁面時,UI 沒有更新,構造函數的部分不再工作,我無法訂閱,但在控制台中每次都會更新值。 所以 UI 沒有被渲染,在我回到組件上后我不能再訂閱那個主題。 我該如何解決這個問題? 謝謝!

您應該unsubscribe subscription您在組件中的subscription

離開組件后您仍然可以在控制台上看到日志這一事實清楚地表明您沒有unsubscribe訂閱,這反過來會導致內存泄漏。

在這里,試試這個:

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

import { NumberService } from "../number.service";

@Component({
  selector: "app-some",
  templateUrl: "./some.component.html",
  styleUrls: ["./some.component.css"]
})
export class SomeComponent implements OnInit {
  interval2 = 0;
  percentSubscription = Subscription;
  statusInterval;

  constructor(private assetItemActionService: NumberService) {
    console.log("takeee");
    this.percentSubscription = this.assetItemActionService.number$.subscribe(
      percent => {
        console.log("set number");
        this.interval2 = percent;
      },
      error => console.log(error)
    );
  }

  ngOnInit() {
    this.interval();
  }

  interval() {
    this.statusInterval = interval(2000).subscribe(x => {
      this.interval2 = x;
      console.log(this.interval2);
      this.assetItemActionService.sendNumber(x);
    });
  }

  ngOnDestroy() {
    this.percentSubscription.unsubscribe();
    this.statusInterval.unsubscribe();
  }
}

PS:您沒有指定您在模板中使用的內容。 所以我剛剛將路由添加到兩個組件( somehello )。


這是供您參考的工作演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM