AngularJS2 学习笔记——Async Data Binding

前端之家收集整理的这篇文章主要介绍了AngularJS2 学习笔记——Async Data Binding前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

网址
https://angular.io/api/common/AsyncPipe

模块
import { AsyncPipe } from ‘@angular/common’;

使用方法

observable_or_promise_expression | async

异步管理订阅Observable或Promise,返回其最后的值。
当有新值时,异步管道给组件置一个变化确认的标记
组件销毁时,异步管道取消订阅避免内存泄露。

示例

下面示例在view上绑定一个Promise。点击
This example binds a Promise to the view. Clicking the 销毁按钮将Promise销毁。

@Component({
  selector: 'async-promise-pipe',template: `<div>
    <code>promise|async</code>: 
    <button (click)="clicked()">{{ arrived ? 'Reset' : 'Resolve' }}</button>
    <span>Wait for it... {{ greeting | async }}</span>
  </div>`
})
export class AsyncPromisePipeComponent {
  greeting: Promise<string>|null = null;
  arrived: boolean = false;

  private resolve: Function|null = null;

  constructor() { this.reset(); }

  reset() {
    this.arrived = false;
    this.greeting = new Promise<string>((resolve,reject) => { this.resolve = resolve; });
  }

  clicked() {
    if (this.arrived) {
      this.reset();
    } else {
      this.resolve !('hi there!');
      this.arrived = true;
    }
  }
}

下面示例是在view上绑定 time Observable,Observable持续更新当前的时间。

@Component({
  selector: 'async-observable-pipe',template: '<div><code>observable|async</code>: Time: {{ time | async }}</div>'
})
export class AsyncObservablePipeComponent {
  time = new Observable<string>((observer: Subscriber<string>) => { setInterval(() => observer.next(new Date().toString()),1000); }); }

下面示例是在订阅时更新值

ts

export class MyPage {
  data:Promise<string>;

  constructor(
    public events:Events
) {
    this.data = this.getPromise();
  }
  getPromise(): Promise<string> {
    return new Promise((resolve,reject) => { this.events.subscribe("my:update",(d,time)=>{ resolve(d); }) }); } ionViewWillUnload() { this.events.unsubscribe('my:update'); }

参考:
http://www.jb51.cc/article/p-epzdjvvu-e.html

原文链接:https://www.f2er.com/angularjs/145487.html

猜你在找的Angularjs相关文章