깜놀하는 해므찌로

Angular Observable Operator 본문

IT

Angular Observable Operator

agnusdei1207 2023. 4. 8. 10:31
반응형
SMALL
import { Component, OnInit, OnDestroy } from '@angular/core';

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

export class ObservableComponent implements OnInit, OnDestroy {
  myArray = [1, 2, 3, 4, 5];
  subscription: Subscription;
  values: number[] = [];

  ngOnInit() {
    // 옵저버블 생성
    const observable$ = from(this.myArray);

    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();
  }
}

반응형
LIST