角度主题和订阅

时间:2019-12-12 14:11:38

标签: angular rxjs

当单击按钮时,我有一个具有方法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,并且在返回组件后,我无法再订阅该主题。我该如何解决?谢谢!

1 个答案:

答案 0 :(得分:1)

您应该unsubscribe subscription在组件中拥有。{p>

离开组件后仍然可以在控制台上查看日志的事实明确表明您尚未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)中。


  

这是您推荐的Working Demo