the problem i have is, every time the component VisOpComponent
is initialized, the subscribed eventemitter gets fired without any call to .next()
. i also added some console.log as shown below to show you that, despite the
subEvtEmitterOnVisualizeBtnClicked
is not initialize but still the log statement in the event subscription can be called and it prints subEvtEmitterOnVisualizeBtnClicked called
please let me know why the event is getting fired without any invokation to .next()
and how to fix it
VisOpComponent:
if(this.subEvtEmitterOnVisualizeBtnClicked) {
if(this.subEvtEmitterOnVisualizeBtnClicked.closed){
console.log("closed subEvtEmitterOnVisualizeBtnClicked")
} else {
console.log("NOT closed subEvtEmitterOnVisualizeBtnClicked")
}
} else {
console.log("subEvtEmitterOnVisualizeBtnClicked not initialized")
}
this.subEvtEmitterOnVisualizeBtnClicked = this._FromAwanti1ToVisOpService.getEmitterOnVisualizeButtonClicked().subscribe((param:number)=>{
console.log("subEvtEmitterOnVisualizeBtnClicked called")
this.visulizationOperationID = param
this.submit()
})
eventemitters:
import { Injectable } from '@angular/core';
import { Component, OnInit, EventEmitter, Output } from '@angular/core';
import { BehaviorSubject, Subject,ReplaySubject } from 'rxjs'
@Injectable({
providedIn: 'root'
})
export class FromAwanti1ToVisOpOfAocAvghInterceptionService {
private emitterOnVisualizeButtonClicked:Subject<number> = new ReplaySubject<number>();
constructor() { }
public emitOnVisualizeButtonClicked(param) {
this.emitterOnVisualizeButtonClicked.next(param)
}
public getEmitterOnVisualizeButtonClicked() {
return this.emitterOnVisualizeButtonClicked.asObservable();
}
logs:
vis-op.component.ts:45 constructor
vis-op.component.ts:59 subEvtEmitterOnVisualizeBtnClicked not initialized
vis-op.component.ts:63 subEvtEmitterOnVisualizeBtnClicked called
If you are absolutely sure that
emitOnVisualizeButtonClicked(param)
never gets called to trigger that unwanted call on line 63 then you may want to check if you have more than one subscription happening - perhapsVisOpComponent
got constructed before and there is nounsubscribe()
?Other reasoning would be the ReplaySubject itself. When a new subscription occurs, add it to the container and replay the values from the cache if any to the corresponding observer.
You could add an if guard
Also important to know that ReplaySubject still replays the cached values before sending the complete or the error error notification to new subsequent subscriptions.
Add an buffer size of one
new ReplaySubject<number>(1)
. It can record and replay a whole series of values or one last value if we give(1)
.