Operator

머맨·2021년 6월 14일
0

오퍼레이터는 옵저버블의 생성,변환,필터링,에러처리의 기능을 하는 함수이다.
오퍼레이터는 새로운 옵저버블을 반환 한다.

1.from 오퍼레이터는 배열과 같은 이터러블을 인자로 전달 받아 옵저버블을 생성한다.
2. mapfilter 오퍼레이터를 사용하여 옵저버블을 변형,필터링 한다.

map filter 오퍼레이터는 자바스크립트의 메소드와 비슷하다.

간단한 예제

// observable.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';

// RxJS 임포트
import { Observable, Subscription, from } from 'rxjs';
import { map, filter, tap } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  template: '<p>{{ values }}</p>'
})
export class ObservableComponent implements OnInit, OnDestroy {
  myArray = [1, 2, 3, 4, 5];
  subscription: Subscription;
  values: number[] = [];

  ngOnInit() {
    // ① 옵저버블 생성
    // 배열과 같은 이터러블을 옵저버블로 만들려면 from 오퍼레이터를 사용
    const observable$ = from(this.myArray);
	
    // RxJS의 pipe() 기능을 이용하여 연산자를 서로 연결할 수 있다.
    // 여러기능들을 단일 기능으로 결합 시키는 역활
    //
    this.subscription = observable$
      .pipe(
        // ② 오퍼레이터에 의한 옵저버블 변형
        map(item => item * 2), // 2, 4, 6, 8, 10
        filter(item => item > 5), // 6, 8, 10
        tap(item => console.log(item)) // 6, 8, 10
      )
      // ③ 옵저버블 구독
      .subscribe(
        // next
        // 지속적으로 데이터를 성공적으로 전달 받으면 할일
        value => this.values.push(value),
        // error
      	// 데이터 받다가 에러나면 할일
        error => console.log(error),
        // complete
      	// 데이터 받기를 완료 하면 할인
        () => console.log('Streaming finished')
      );
  }

  ngOnDestroy() {
    // ④ 옵저버블 구독 해지
    this.subscription.unsubscribe();
  }
}
profile
코맨코맨

0개의 댓글