angular2中 AsyncPipe的使用与input中pipe的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chongchong1325/article/details/89314054

常见的使用方法,在以前的文章中有过介绍,这里就不赘述了,以下讲解下我最近在项目当中用到的用法

1,关于异步管道(AsyncPipe)

使用 AsyncPipe 我们可以直接在模板中使用 Promise 和 Observable 对象,而不用通过定义一个类的成员属性来存储返回的结果。

AsyncPipe 订阅一个 Observable 或 Promise 对象,并返回它发出的最新值。 当发出新值时,异步管道会主动调用变化检测器的 markForCheck() 方法,标识组件需执行变化检测。 当组件被销毁时,异步管道自动取消订阅,以避免潜在的内存泄漏。

具体的示例如下:

import { Pipe, PipeTransform } from '@angular/core';
import {
  Observable,
  Subscriber,
  throwError as observableThrowError
} from 'rxjs';


@Pipe({ name: 'billType' })
export class BillTypesReform implements PipeTransform {
  constructor(private dictService: DictService) {}
  transform(value: string) {
    return new Observable((observer: Subscriber<any>) => {
      this.dictService.getBillTypes().subscribe(res => {
        observer.next(this.trans(value, res));
      });
    });
  }

  trans(value, data) {
    for (let i = 0, len = data.length; i < len; i++) {
      if (value === data[i].code) {
        return data[i].name;
      }
    }
    return value;
  }
}

引入pipe之后,在html中的使用方法如下:

<span>{{data?.billType || '-' | billType| async}}</span>

使用场景:

选项需要从后台接口异步获取数据的时候。

2.input使用pipe

<input nz-input name="quotaType" type="text" [ngModel]="condition?.quotaType | quotatype" (ngModelChange)="condition.quotaType=$event">

下面也介绍几篇描述比较好的文章:

https://segmentfault.com/a/1190000008759314

https://blog.csdn.net/maoguiyou/article/details/53745838

猜你喜欢

转载自blog.csdn.net/chongchong1325/article/details/89314054