异步管道 AsyncPipe

在本篇文章中,我将主要从四个方面来介绍异步管道
1、什么是异步管道
2、为什么使用异步管道
3、如何将AsyncPipe与Observable 、Promise结合在一起
4、如何将它与插值数据绑定和不同的指令(如 *ngIf 和 *ngFor)一起使用。

首先,什么是AsyncPipe?

来自angular官方文档:AsyncPipe会订阅一个Observable或者Promise并返回它发出的最近的一个值,当新值到来时,AsyncPipe会将该组件标记为需要进行变更检测,当组件被销毁时,AsyncPipe会自动取消订阅,以消除潜在的内存泄漏问题。
angular 异步管道允许订阅 angular 模板语法内的 observable,并负责自动取消订阅 observable。
让我们来看一个例子,这段代码的作用就是一个计数的,没过1s就将value+1并输出,

import { Component } from '@angular/core'
import { Observable } from 'rxjs'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  observable: Observable<number>

  ngOnInit() {
    this.observable = Observable.create(observer => {
      let value = 0
      const interval = setInterval(() => {
        observer.next(value)
        value++
      }, 1000)

      return () => clearInterval(interval)
    })
  }
}

现在我们想将该值在页面中显示出来,就可以引用该observable,并将它传入到异步管道中进行解析。

<p>{{ observable | async }}</p>

angular的httpclient本身返回的就是一个Observable,和AsyncPipe简直绝配。

为什么要使用异步管道?

这时候有一些人会说,平时直接用subscribe更新属性值也挺方便的,为什么要使用异步管道呢?
ok,现在思考一下如果不适用异步管道,我们上面的代码要多哪些内容呢?
1、需要再ngOnint中添加对observable的订阅

 this.subscription = this.observable.subscribe(
      value => (this.latestValue = value)
    )

2、为了防止内存泄漏,还需要添加unsubscribe,这就要使用钩子函数ngOnDestory(如果时httpclient返回的是可以不写的,挖个坑,后面另写一篇文章讲讲)

ngOnDestroy() {
    this.subscription.unsubscribe()
  }

看其他人的博客又学会了另一种写法,使用takeUntil 操作符负责取消订阅,这种方法在处理一个订阅中有多个 observable 时特别有用,我们不需要保留所有订阅的列表。

//subscribe
this.observable$
          .pipe(takeUntil(this.unsubscribe$))
          .subscribe(value => this.latestValue = value);
  
//unsubscribe
  ngOnDestroy(){
    this.unsubscribe$.next();
    this.unsubscribe$.complete();
  }

当使用 angular 异步管道时,这些额外的代码是不需要的,一旦组件被销毁,管道本身就会负责取消订阅 observable, 所以异步管道使我们的代码更干净。此外AsyncPipe使用的时onPush变更检测策略,对组件性能起到很好的作用,所以说我们应该尽可能多的去使用异步管道。

如何将AsyncPipe与NgIf、NgFor结合使用?

NgIf

<p *ngIf="(observable | async) > 5">{{ observable | async }}</p>

NgFor

<p *ngFor="let item of items | async">{{ item }}</p>

总结

始终相信一点:你所能想到的,angular都为你做好了。如果觉得本文对您有用,就点个赞吧

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值