옵저버블 기본

lee jae hwan·2022년 8월 31일
0

RxJS

목록 보기
5/21
import { Component, OnInit } from '@angular/core';

import { from, fromEvent } from 'rxjs';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {


  postsArray = [
    {title:'book1', description:'this is my book1'},
    {title:'book2', description:'this is my book2'},
    {title:'book3', description:'this is my book3'},
  ];
  // 외부데이터
  

  postsArrayStream$ = from(this.postsArray);
  // 배열테이터를 가공처리하기위해 스트림을 생성하고 넣는다.


  promise = new Promise((resolve, reject)=>{
    setTimeout(() => {
      resolve('promise resolved');
    }, 2000);
  });
  // 비동기작업있다고 가정
  

  promiseStream$ = from(this.promise);
  // Promise비동기 작업을 RxJS로 처리하기위해 Promise객체로부터 옵저버블객체생성
  
  // from메소드로 왠만한 소스데이터를 옵저버블객체로 만들 수 있다.
  
  
  constructor() { 
    this.postsArrayStream$.subscribe({
      next:(val)=>{console.log(val)},
      error:(err)=>{console.log(err)},
      complete:()=>{console.log('completed')},
    });
    // 스트림에 subscribe메소드에 옵저버를 등록하면 스트림은 방출하기 시작한다.
    // 옵저버는 콜백함수개체형식으로 설정한다.
    

    this.promiseStream$.subscribe({
      next:(val)=>{console.log(val)},
      error:(err)=>{console.log(err)},
      complete:()=>{console.log('completed')},
    })
    // promise객체도 옵저버블객체로 되었기때문에 구독처리는 위와 같이하면 된다.
    // 전달되는 매개변수는 promise객체가 전달한다.
    

  }

  ngOnInit(): void {
    fromEvent(document.querySelector('#link-click')!,'click').subscribe({
      next:(val)=>{console.log(val)},
      error:(err)=>{console.log(err)},
      complete:()=>{console.log('link completed')},
    })
    // fromEvent메소드는 브라우저이벤트를 옵저버블 스트림객체로 만들어준다.
    // 구독처리는 위와 같으며 전달되는 매개변수는 이벤트객체다
    
    
  }

}

0개의 댓글