iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 20
1
Modern Web

Angular 8 從推坑到放棄系列 第 20

[Day 19] 初步使用 Observable

為什麼使用rxjs

RxJS是一組可以用來處理非同步、以及同步事件的一個JavaScript Library

能幫助你快速地使用像是Ajax、Server Work、SetTimeout 等其他非同步的事件

而它主要可以分為兩大類:

  1. 非同步的程式
  2. 畫面事件處理

之前在討論的 Zone.js 時提到

傳統上我們在使用非同步的時候,會需要確保我們的程式執行順序不會被打亂

因此在非同步的程式開發上,我們多半會採用 CallBack Function來解決問題,讓我們執行順序能正常Work

但是有些情況下你可能很常會遇到一些特殊的需求:

我需要先發送一個非同步的請求來處理使用者的資料,接著在資料回傳後使用者操作過後,又再發一個請求給Server

這時候我們的程式就會透過CallBack Function來幫助我們發送第二個請求

使用基本的 Observable

export class HomeComponent implements OnInit, OnDestroy {
  private firstSubscription: Subscription;
  constructor() { }

  ngOnInit() {
    this.firstSubscription = interval(1000).subscribe(count => {
      console.log(count);
    });
  }
  ngOnDestroy() {
    this.firstSubscription.unsubscribe();
  }

}

客制 Observable

除了使用 rxjs 內建的方法外, 還可以針對需求撰寫自己需要的 Rxjs

export class HomeComponent implements OnInit, OnDestroy {
  private firstSubscription: Subscription;
  constructor() { }

  ngOnInit() {
    this.firstSubscription = interval(1000).subscribe(count => {
      console.log(count);
    });
    const customIntervalObservable = Observable.create(observer => {
      let count = 0;
      setInterval(() => {
        observer.next(count);
        if (count === 2) {
          observer.complete();
        }
        if (count > 3) {
          observer.error(new Error('Count is greater 3'));
        }
        count++;
      }, 1000);
    });
    this.firstSubscription = customIntervalObservable.subscribe(data => {
      console.log(data);
    }, error => {
      console.log(error);
    });
  }
  ngOnDestroy() {
    this.firstSubscription.unsubscribe();
  }

}

上面的範例建立了一個 Observable,建立了每一秒顯示在 Console

參考

  1. 希望是最淺顯易懂的 RxJS 教學
  2. RxJS 快速入門 教你如何快速理解RxJS用途以及使用方式

上一篇
[Day 18] 如何使用 Angular Routing
下一篇
[Day 20] Angular 使用 React Form
系列文
Angular 8 從推坑到放棄30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言