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);
}
}