티스토리 뷰

참고 페이지 - 다양한 구독 취소 방법이 나와있다!

https://netbasal.com/when-to-unsubscribe-in-angular-d61c6b21bad3

연습했던 ts파일 소스.

항상 예제 찾아보면 전체적인 소스가 있는게 이해도되고 좋더라구요.

observable을 unsubscribe하기 위해 넣었던 소스는

subscription지정해주고 해당 명칭의 subscription을 unsubscribe! 클래스쪽에 ondestroy추가.

 

 

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

@Component({
  selector: 'app-observable1',
  templateUrl: './observable1.component.html',
  styleUrls: ['./observable1.component.css']
})
export class Observable1Component implements OnInit , OnDestroy{
  combinedTotal:number = 0;
  private pass$: Observable<any>;
  private run$: Observable<any>;
  teams = [
    {
      passing:0,
      running:0,
      total:0
    }
  ];
  runSubs: Subscription;

  ngOnInit() {
    //passing
    this.pass$ = new Observable(observer => {
      this.playLoop(observer);
    });
    this.pass$.subscribe(
      data => {
        this.teams[0].passing += data.yards;
        this.addTotal(data.yards);
      }
    );

    // running
    this.run$ = new Observable(observer => {
      this.playLoop(observer);
    });
    this.runSubs = this.run$.subscribe(
      data => {
        this.teams[0].running += data.yards;
        this.addTotal(data.yards);
      }
    );

    // combined total
    this.pass$.subscribe(
      data => {
        this.combinedTotal += data.yards;
      }
    );
    this.run$.subscribe(
      data => {
        this.combinedTotal += data.yards;
      }
    );
  }

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

playLoop(observer) {
  const time = this.getRandom(500, 2000);
  setTimeout(() => {
    observer.next(
      {
        // team: this.getRandom(0,2),
        yards: this.getRandom(0, 20)
      });
    if(this.combinedTotal < 1000) {
      this.playLoop(observer)
    }
  }, time);
}

addTotal(yards){
  this.teams[0].total += yards;
}

getRandom(min, max){
  return Math.floor(Math.random() * (max - min)) + min;
}

}

'Javascript > Angular' 카테고리의 다른 글

[Angular7] http서비스 오류 해결  (0) 2020.04.01
[Angular] metarial, animation 모듈 설치 명령어  (0) 2020.04.01
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함