반응형

어씽크(asynchronous) 핸들러입니다. 솔찍히 Promise와 모가 다른지 모르겠지만... 말이죠.

 

Ajax와 같은 기존에 사용하던 기능이 있는데 생소한 Observable을 사용하려니 이만저만 힘든게 아니라는 생각이 들었습니다.

하지만 Router를 이용하면서 이미 Observable를 이용했다고 하니 외부 라이브러리를 사용할 필요가 없다는 것을 알았습니다.

 

Route.params.subscribe()에서 params가 Observable이였습니다.

 

다음은 Observable을 사용하는 간단한 예제입니다.

import { Component, OnDestroy, OnInit } from '@angular/core';

import { interval, Subscription } from 'rxjs';

export class HomeComponent implements OnInit, OnDestroy {

  private firstObsSubscription: Subscription;

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

  ngOnDestroy(): void {
    this.firstObsSubscription.unsubscribe();
  }

}

직접 unsubscribe해야 합니다. route.params에서는 Angular가 뒤에서 unsubscribe까지 지원해 주었습니다.

 

data(customedName), error, complete를 이용하기 예제

const customIntervalObservable = Observable.create(observer => {
  let count = 0;
  setInterval(() => {
    observer.next(count);
    if (count == 5) {
      observer.complete();
    }
    if (count > 3) {
      observer.error(new Error('Count is greater 3!'));
    }
  count++;
  }, 1000);
      
this.firstObsSubscription = customIntervalObservable.subscribe(data => {
    console.log(data);
  }, error => {
    console.log(error);
    alert(error.message);
  }, () => {
    console.log('Completed!');
  });
}

error혹은 complete을 만나면 event emit은 끝납니다.

 

Operators를 이용해서 filter, map등 이용할 수 있습니다.

import { map, filter } from 'rxjs/operators';

customIntervalObservable.pipe(filter(data => {
      return data > 0;
    }), map((data: number) => {
      return 'Round: ' + (data+1);
    })).subscribe...

Subject는 service를 이용하여 컴포넌트간 통신을 할 때 유용합니다.

 

Observable대신, Subject로 할 수 있습니다. 두 개의 차이는 Passvie와 Active로 나눌 수 있습니다.

Subject를 사용하면 수동으로 next()를 사용해야 하는데,


다만 @Output를 사용할 때, EventEmitter대신 Subject를 사용시 주의해야 합니다.

 

Useful Resources:
Official Docs: https://rxjs-dev.firebaseapp.com/
RxJS Series: https://academind.com/learn/javascript/understanding-rxjs/
Updating to RxJS 6: https://academind.com/learn/javascript/rxjs-6-what-changed/

 

RxJS 6 - What Changed?

RxJS 6 changes everything! Or does it? It certainly breaks your imports and operator usage. Time for some (quick!) fixes!

academind.com

 

자료 출처 : https://www.udemy.com/share/1000imAkEeeVhSQ34=/

반응형

'프로그래밍 > Angular' 카테고리의 다른 글

FormHandling - Reavice  (0) 2019.07.02
Handling Form - Template Driven  (0) 2019.07.02
Router 정리  (0) 2019.06.25
Routes  (0) 2019.06.17
Providers - Hierarchical Injector  (0) 2019.06.16

+ Recent posts