programing

Angular2에서 구독을 취소하는 방법

javajsp 2023. 8. 22. 21:56

Angular2에서 구독을 취소하는 방법

Angular2에서 구독을 취소하려면 어떻게 해야 합니까?RxJS는 폐기 방법이 있는 것 같은데, 어떻게 접근해야 할지 모르겠습니다.이벤트 이미터에 액세스할 수 있고 다음과 같이 구독할 수 있는 코드가 있습니다.

var mySubscription = someEventEmitter.subscribe(
    (val) => {
        console.log('Received:', val);
    },
    (err) => {
        console.log('Received error:', err);
    },
    () => {
        console.log('Completed');
    }
);

사용 방법mySubscription구독을 취소하시겠습니까?

구독을 취소하시겠습니까?

mySubscription.unsubscribe();

저도 2센트 넣었다고 생각했어요.다음 패턴을 사용합니다.

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

@Component({
    selector: 'my-component',
    templateUrl: 'my.component.html'
})
export class MyComponent implements OnInit, OnDestroy {

    private subscriptions: Array<Subscription> = [];

    public ngOnInit(): void {
        this.subscriptions.push(this.someService.change.subscribe(() => {
            [...]
        }));

        this.subscriptions.push(this.someOtherService.select.subscribe(() => {
            [...]
        }));
    }

    public ngOnDestroy(): void {
        this.subscriptions.forEach((subscription: Subscription) => {
            subscription.unsubscribe();
        });
    }
}

편집

며칠 전에 설명서를 읽었는데 더 권장되는 패턴을 발견했습니다.

반응형 X/RxJS/구독

찬성:

내부적으로 새 구독을 관리하고 몇 가지 깔끔한 체크를 추가합니다.기능:)에서 이 방법을 선호합니다.

단점:

코드 흐름이 무엇인지, 구독이 어떻게 영향을 받는지는 100% 명확하지 않습니다.코드만 봐도 폐쇄된 구독을 어떻게 처리하는지, 구독 취소가 호출되면 모든 구독이 닫히는지 알 수 없습니다.

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

@Component({
    selector: 'my-component',
    templateUrl: 'my.component.html'
})
export class MyComponent implements OnInit, OnDestroy {

    private subscription: Subscription = new Subscription();

    public ngOnInit(): void {
        this.subscription.add(this.someService.change.subscribe(() => {
            [...]
        }));

        this.subscription.add(this.someOtherService.select.subscribe(() => {
            [...]
        }));
    }

    public ngOnDestroy(): void {
        /*
         * magic kicks in here: All subscriptions which were added
         * with "subscription.add" are canceled too!
         */
        this.subscription.unsubscribe();
    }
}

편집: angular2가 사용하는 RxJS 5에는 적용되지 않습니다.

저는 당신이 일회용에서 폐기 방법을 찾고 있다고 생각했을 것입니다.

구독 메서드가 일회용(링크)을 반환합니다.

문서에서 더 명확하게 찾을 수는 없지만, 이것은 작동합니다(jsbin).

var observable = Rx.Observable.interval(100);

var subscription = observable.subscribe(function(value) {
   console.log(value);
});

setTimeout(function() {
  subscription.dispose();           
}, 1000)

이상하게도, 구독 취소는 당신에게 효과가 있는 것 같은데, 나에게는 효과가 없습니다.

ng2에 대한 관찰 가능한 구독 취소에 대한 너무 많은 다양한 설명이 정답을 찾는 데 많은 시간이 걸렸습니다.아래는 작동 예입니다(마우스 이동을 조절하려고 했습니다).

import {Injectable, OnDestroy} from "@angular/core";
import {Subscription} from "rxjs";

@Injectable()
export class MyClass implements OnDestroy {
  
  mouseSubscription: Subscription; //Set a variable for your subscription
  
  myFunct() {
    // I'm trying to throttle mousemove
    const eachSecond$ = Observable.timer(0, 1000);
    const mouseMove$ = Observable.fromEvent<MouseEvent>(document, 'mousemove');
    const mouseMoveEachSecond$ = mouseMove$.sample(eachSecond$);
    
    this.mouseSubscription = mouseMoveEachSecond$.subscribe(() => this.doSomethingElse());
  }

  doSomethingElse() {
    console.log("mouse moved");
  }
  
  stopNow() {
    this.mouseSubscription.unsubscribe();
  }
  
  ngOnDestroy() {
    this.mouseSubscription.unsubscribe();
  }
  
}

ngOnDestroy(){
   mySubscription.unsubscribe();
}

구성 요소를 제거하는 동안 rxjs 구독 취소를 선호합니다. 즉, 불필요한 메모리 누수를 방지하기 위해 DOM에서 제거합니다.

저는 개인적으로 제목을 사용하여 다음과 같은 방법으로 달성할 수 있는 수명 주기 제거 단계에서 구성 요소가 가질 수 있는 모든 구독을 닫는 것을 선호합니다.

import { Component} from '@angular/core';
import { Subject } from "rxjs/Rx";

@Component({
  selector:    'some-class-app',
  templateUrl: './someClass.component.html',
  providers:   []
})

export class SomeClass {  

  private ngUnsubscribe: Subject<void> = new Subject<void>(); //This subject will tell every subscriptions to stop when the component is destroyed.

  //**********
  constructor() {}

  ngOnInit() {

    this.http.post( "SomeUrl.com", {}, null ).map( response => {

      console.log( "Yay." );

    }).takeUntil( this.ngUnsubscribe ).subscribe(); //This is where you tell the subscription to stop whenever the component will be destroyed.
  }

  ngOnDestroy() {

    //This is where we close any active subscription.
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }
}

takeUntil 연산자와 같은 RxJS 연산자를 사용하는 것이 좋습니다.아래는 사용법을 보여주는 코드 스니펫입니다.

import { Component, OnInit, OnDestroy } from '@angular/core';
import { interval, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})
export class AppComponent implements OnInit, OnDestroy {
    private ngUnsubscribe = new Subject();

    constructor() { }

    ngOnInit() {
        var observable1 = interval(1000);
        var observable2 = interval(2000);

        observable1.pipe(takeUntil(this.ngUnsubscribe)).subscribe(x => console.log('observable1: ' + x));
        observable2.pipe(takeUntil(this.ngUnsubscribe)).subscribe(x => console.log('observable2: ' + x));
    }

    ngOnDestroy() {
        this.ngUnsubscribe.next();
        this.ngUnsubscribe.complete();
    }
}

항목에 대한 자세한 설명은 여기에서 확인할 수 있습니다.

사용하다

if(mySubscription){
  mySubscription.unsubscribe();
}
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { SomeAPIService } from '../some_file/someAPIService.service.ts

@Component({
  templateUrl: './your_Page.html',
  styleUrls: ['./your_Styles.scss']
})

export class (your class) implements OnInit, OnDestroy {
   // This is a subject variable at it simplest form 
     private unsubscribe$ = new Subject<void>();

     constructor (private someAPIService : SomeAPIService) {}
   
     ngOnit(): void { 
       this.someAPIService.getTODOlist({id:1})
        .pipe(takeUntil(this.unsubscribe$))
         .subscribe((value: SomeVariable) => {
         // What ever value you need is SomeVariable
      },)
    }


     ngOnDestroy(): void {
    // clears all, page subscriptions 
      this.unsubscribe$.next();
      this.unsubscribe$.complete();
     }
`}

언급URL : https://stackoverflow.com/questions/34442693/how-to-cancel-a-subscription-in-angular2