angular Observable 怎么自动取消订阅

本文介绍了在Angular开发中,如何使用RxJS的Observable时避免因未取消订阅导致的问题。通过引入ngneat/until-destroy库,可以在组件销毁时自动取消订阅,防止内存泄漏。示例代码展示了在InboxComponent中如何使用until-destroy装饰器来确保在组件被销毁时自动取消订阅。
摘要由CSDN通过智能技术生成

rxjs 的 Observable(可观察对象)极大的方便了我们的开发,但是当 subscribe(订阅) 没有多次时,前一个订阅没有取消,导致订阅方法被执行了多次。

  ngOnInit(): void {
    this.query.select().subscribe((data) => {
      console.log(data);
    });
  }

这种情况怎么办呢,可以手动取消订阅,但是有没有办法在 页面Destroy 后自动取消订阅呢?

使用 until-destroy

npm install @ngneat/until-destroy

 使用方法:

import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy';

@UntilDestroy()
@Component({
  selector: 'app-welcome',
  templateUrl: './welcome.component.html',
  styles: [],
})
export class InboxComponent {
  ngOnInit(): void {
    this.query
      .select()
      .pipe(untilDestroyed(this))
      .subscribe((data) => {
        console.log(data);
      });
  }
}

使用后当页面 destroy 时会生动取消订阅。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值