AngularJS2 学习笔记5 Async Data Binding
Posted 编程圈
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AngularJS2 学习笔记5 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);
参考:
以上是关于AngularJS2 学习笔记5 Async Data Binding的主要内容,如果未能解决你的问题,请参考以下文章