BehaviorSubject is executed more than once

不羁岁月 提交于 2019-12-20 04:50:30

问题


I am using angular 4 for my app and I use behaviorSubject to communicate between component, everythings were working fine

Here is my code:

export class Globals {
loadStudentsByClass: BehaviorSubject<string> = new BehaviorSubject<string>(null);
}

export class ClassComponent implements OnInit {
selectNewClass() {
    console.log('About to select new class', this.selectedClass);
    this.globals.loadStudentsByClass.next(this.selectedClass); 
    this.globals.changeClassBehavior.next(true);
    this.router.navigateByUrl('');
  }
}

export class StudentComponent implements OnInit {
    this.globals.loadStudentsByClass.subscribe(value => {
          if (!isNullOrUndefined(value) && this.selectedClass !== value) {
            console.log('loadStudentsByClass=> home');
            this.loadStudentsByClass(this.selectedClass);
          }
        });
}

So, I have the component ClassComponent who triggers the StudentComponent to call the function loadStudentsByClass.

This is the only place where I call this behavior subject, but I find my behavior Subject emitted more than once

The problem is why behaviorSubject execute loadStudentsByClass more than once although this.globals.loadStudentsByClass.next(this.selectedClass); is called only one time

By the way the number of execution depends on the numbers of views I visited in the application


回答1:


You probably forgot to unsubscribe in your StudentComponent when the components gets destroyed. Save the subscription in a class variable and in ngOnDestroy() lifecycle hook call subscription.unsubscribe()




回答2:


This will call twice, because whenever the behaviourSubject changes it will emit the latest values. Previously it was null (as default value) which you have given it and next when the service response came you are doing next so it will emit the latest value after change, which is fair enough. For your code you should only check for

if(value){// do the stuff here}



回答3:


Try a replay subject that has no initial value but will still cache your stream:

export class Globals {
loadStudentsByClass = new ReplaySubject<string>(1);
}


来源:https://stackoverflow.com/questions/51403138/behaviorsubject-is-executed-more-than-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!