填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫Home

AsyncPipe

從一個非同步回執中解出一個值。

Unwraps a value from an asynchronous primitive.

檢視"說明"...

      
      {{ obj_expression | async }}
    

Exported from

輸入值

obj Observable | Subscribable | Promise

說明

async 管道會訂閱一個 ObservablePromise,並返回它發出的最近一個值。 當新值到來時,async 管道就會把該元件標記為需要進行變更檢測。當元件被銷燬時,async 管道就會自動取消訂閱,以消除潛在的記憶體洩露問題。

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.

Further information available in the Usage Notes...

使用說明

例子

Examples

這個例子把一個 Promise 繫結到了檢視中。點選 Resolve 按鈕就會解析此 Promise。

This example binds a Promise to the view. Clicking the Resolve button resolves 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;
    }
  }
}
    

還可以把 async 用於 Observable。下面的例子就把 time 這個 Observable 繫結到了檢視上。這個 Observable 會不斷使用當前時間更新檢視。

It's also possible to use async with Observables. The example below binds the time Observable to the view. The Observable continuously updates the view with the current time.

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