【问题标题】:Multiple Subscription of observable does not work sometimes多次订阅 observable 有时不起作用
【发布时间】:2019-05-14 08:39:04
【问题描述】:

我创建了一个observable,我是subscribing,每次在button 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 ..
  }); 
}
}

主服务

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 之后取消订阅这个 observable 还是必须做其他事情

【问题讨论】:

  • 你也可以展示MainService类的实现吗?除非您使用BehaviorSubject,否则您的订阅回调将仅在发出事件时运行
  • @AmitChigadani 能否请您详细说明此声明 And your subscription call back will run only when event is emitted ,因为这里会发出 on click of button 事件,所以为什么不按下按钮时在这里调用
  • @AmitChigadani MainService 仅具有 process$ Observable 定义
  • 点击按钮时,您订阅了process$ 事件,而不是发出事件。所以多次点击只会创建新的Subscriptions
  • @AmitChigadani,如果您在每个订阅中看到正在运行observer.next(),那么我认为它应该调用回调。我在写吗?

标签: javascript angular observable


【解决方案1】:

这是适合我的解决方案。我关注这个link 它对我有帮助。

以下将是这个问题的解决方案。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    • 2020-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多