Angular - async pipe (Observable)

  • 3170
  • 0
  • 2018-05-24

介紹 async pipe的用法

async pipe 通常式用來簡化component的程式碼,如果資料來源是Observable(觀察者物件),

單純只想把資料顯示在template的時候,就可以考慮使用 pipe: async

async 會把 Observable(觀察者物件)  的物件傳給 async 的 Pipe元件,

然後幫你做 subscribe(訂閱)的動作,得到資料之後再回傳到 template,

讓使用者可以直接繼續做ngFor或是其他 Structure Directive 的作業

使用 async 就不需要在component內做subscribe(訂閱) 的動作。

舉例來說:

先在Service內建立一個Function :GetData() ,回傳的時候是提供 Observable<Object>

真正要subscribe(訂閱) 的時間點則是交由使用Service的 component 自己決定。

< subscribe 理應由component 自行決定,因為取回的資料實體應該是存在component ,而不應該放在 service 內 >


constructor(private http: HttpClient) {}

// 只提供 Observable<Object>
GetDatat() {
  return this.http.get('http://localhost:4200/api/articles.json');
}

 

接著我在component 內宣告一個型態為 Observable 的物件:data$

變數名稱最後加上$結尾,是宣告 Observable物件的命名習慣,泛型要記得加上<any>

在ngOnInit() 裡面我去初始化 data$的資料,如果要使用  async 的話,

就不需要在component內先做subscribe(訂閱)的動作,subscribe的動作交給 pipe: async 去執行就好

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { Observable } from 'rxjs/Observable'; // 會自動import 

@Component({
  selector: 'app-article-list',
  templateUrl: './article-list.component.html',
  styleUrls: ['./article-list.component.css']
})
export class ArticleListComponent implements OnInit {
  constructor(public datasvc: DataService) {}

  //宣告一個型別為Observable的物件:data$
  data$: Observable<any>;

  counter = 0;

  ngOnInit() {
    this.data$ = this.datasvc.GetData();
  }

}

最後直接在template 裡面使用 pipe: async

<article class="post" *ngFor="let item of data$|async">
    <app-article-header [item]="item"></app-article-header>
    <app-article-body [item]="item" [Counter]="counter"></app-article-body>
</article>

在這邊的pipe: async 就會自動幫你做 subscrible 的動作

結論:

單純只想把資料顯示在template的時候,就可以使用async: pipe來簡化component內的程式碼(在component少寫subscrible那段)