可观察的多个订阅有时不起作用

时间:2018-12-13 07:05:11

标签: javascript angular observable

我每次在observable事件中都创建了一个subscribingbutton click

import {Component} from '@angular/core';
import {MainService} from '..\services\main-service';
@component({
 selector:'app-main',
 style:'',
 template:'<div> <button click="processing()">Processing</button></div>'   
})

exports class AppMain{

 constructor(private mainService: MainService){
}

processing(){
  this.mainService.process$.subscribe((res)=>{
    // doing something here ..
  }); 
}
}

MainService

import {OnInit} from '@angular\core'; 
import {Observable} from 'rxjs\Observable'; 
export class MainService implements OnInit{
   public process$;
   constructor(){
     this.process$ = new Observable((observer)=>{
         // doing something here
         observer.next();
     });
  }
}

现在,每当我多次单击此按钮时,有时这种可观察到的功能就无法运行。

我是否必须在每个subsciption之后取消订阅此可观察到的消息,或者必须执行其他操作

1 个答案:

答案 0 :(得分:0)

这是对我有用的解决方案。我遵循此link,它对我有帮助。

以下将解决此问题。

processing(){
  const processUnsubscribe$;
  processUnsubscribe$ = this.mainService.process$.subscribe((res)=>{
  // doing something here ..

  //Now unsubscribe here if you subscribe this multiple times.
   processUnsubscribe$.unsubscribe();   
  });   
 }
}