1

I've a an array in my serviceA and I add data to that array in componentA and remove data from that array in componentB (this is an entryComponent). I wanted to always know the current length of the array from componentA. I've created a variable and an event in the serviceA that updates the length of the variable upon calling the addData (a service method) from componentA and also upon removing the removeData (a service method) from componentB. However, when I call addData I could see that my componentA gets the updated length of the array, but when I call the removeData from componentB, componentA doesn't get the updated length of the array. Can someone help me what is wrong here.

Service code:

      @Injectable()
      export class serviceA implements OnInit {
      public totalCurrentLength = 0;
      public dataArray = [];
      dataArrayChanged: Subject<any> = new Subject<any>();

      constructor(){
      this.dataArrayChanged.subscribe((value) => {
       this.totalCurrentLength = value;
      })       
    }

    addData(data){
     this.dataArray.push(data);
     this.dataArrayChanged.next(this.dataArray.length); 
    }

     removeData(index){
     this.dataArray.splice(index, 1);
     this.dataArrayChanged.next(this.dataArray.length); 
    }        

}

componentA:

    export class componentA implements OnInit {
    public currentArrayTotal = 0;
    constructor(
    serviceAObj:serviceA){}
    this.addData(data){
      this.serviceAObj.addData(data);
      this.currentArrayTotal = this.serviceAObj.totalCurrentLength;
    } 
} 

ComponentB:

 export class componentB implements OnInit {
    constructor(
    serviceAObj:serviceA){}
    this.removData(index){
      this.serviceAObj.removeData(index);
    } 
} 
Ajay Srikanth
  • 893
  • 3
  • 15
  • 42

1 Answers1

0

I think what is happening is this.serviceAObj.addData(data); is executed, which kicks off an event.

Then before that event's listener this.dataArrayChanged.subscribe(... has a chance to update the serviceAObj.currentArrayTotal value, the value is set

this.currentArrayTotal = this.serviceAObj.totalCurrentLength;

So you have a race condition happening between these two lines:

this.serviceAObj.addData(data);
this.currentArrayTotal = this.serviceAObj.totalCurrentLength;

The "reactive" approach to this problem is to expose the Subject in ServiceAObj and do the listening to it in ComponentA.

Jesse
  • 1,945
  • 11
  • 15