簡體   English   中英

如何停止通過可觀察到的運算符(如debounceTime和switchMap)用於異步驗證的Observable.timer

[英]How to stop the Observable.timer which is used through observable operators like debounceTime and switchMap for asynchronous validations

從該頁面導航到另一頁面時,我需要停止Observable.timer。 下面是我在項目中使用的代碼。

import { Component, ChangeDetectorRef, OnDestroy } from '@angular/core';
import { NavController, MenuController } from 'ionic-angular';
import {Observable, Subject}from 'RxJs/Rx';

export class SettingsPage extends BasePage implements OnDestroy {
ionViewDidLoad() {
let initial: boolean = true;

this.serverUrlStream
        .debounce((val)=> Observable.timer(initial ? 0 : 500))  
        .switchMap(val => {     
                this.canLeave = false;  
                this.apiClientService.ocServiceUrl = val;
                return Observable.fromPromise(this.apiClientService.getHospitals());
        })
        .catch((err, caught)=>{
            console.log(err);
            return caught;  // Continue after error
        })
        .subscribe((hospitals: Hospital[]) => {
            this.hospitals = hospitals;
            if (hospitals.length > 0) {
                this.settings.hospitalInstallId = hospitals[0].InstallId;
                this.canLeave = true;                   
                this.cd.detectChanges();
            }
        });


    this.serverUrlStream.next(this.settings.serverUrl);
    initial = false;
}
//I tried like below to stop the timer when I left from this page.

ngOnDestroy(){
this.serverUrlStream.unsubscribe();
}

}

上面的代碼仍然無法正常工作,每5秒運行一次ajax調用。 用戶離開當前頁面時,誰能幫助我停止Observable.timer

取消訂閱ngOnDestroy是正確的。 您只是語法有點錯誤。

首先,您需要將實際訂閱分配給變量,例如this.serverUrlSubscription = this.serverUrlStream.debounce(...)...subscribe(...);

您應該在其中聲明serverUrlSubscription: Subscription; 首先作為您班級的成員(可以從rxjs/Subscription導入Subscription類型)。

然后,您可以簡單地執行this.serverUrlSubscription.unsubscribe(); 在您的ngOnDestroy中分離並銷毀訂閱

第二種方法是在switchMap運算符之后使用takeUntil(this.router.events.filter((event) => event instanceof NavigationStart)在該操作中,您首先必須將有角度的路由器注入this.router

但我建議您使用ngOnDestroy

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM