Receiving multiple instances of data from Behavior Subject every time component is initialised

后端 未结 1 872
走了就别回头了
走了就别回头了 2021-01-20 17:24

I have a simple router where i am calling a service and receiving the data from the behavior Subject...When i navigate to another route and comeback i am receiving multiple

相关标签:
1条回答
  • 2021-01-20 17:56

    The behavior is expected.

    export class Sample1 {
      constructor(public srvc:HeroService) {
          this.srvc.Data.subscribe(data=> {
            console.log(data);
          });
          this.srvc.GetData();
      }
    }
    

    In the constructor you subscribe to srvc.Data and because Data is a BehaviorSubject it returns the most recent emitted value. You initialize Data with null, therefore at first there is no data.

    Then in the constructor you call this.srvc.GetData() this causes an event to be emitted and be received by the subscription (the lines before).

    If you navigate away and back, then Sample1 is initialized again and the constructor is executed. The first thing is that is subscribes to srvc.Data. and it gets the last emitted value which is Received Data from the previous call to GetData() (when we first navigated to Heroes).

    The next thing is the call to this.srvc.GetData() which again emits Received Data and the subscription gets this value passed.

    Workaround

    To fix it you could move the call to this.srvc.GetData(); to the service instead like

    @Injectable()
    export class HeroService {
      Data: BehaviorSubject<RepairOrder> = new BehaviorSubject(null);
    
      constructor() {
        this.GetData();
      }
    
      GetData(){
        this.Data.next('Recieved Data');
      }
      DestroySubject(){
        //alert('hi');
      }
    }
    

    Plunker example

    0 讨论(0)
提交回复
热议问题