简体   繁体   中英

How to execute a subscription ngOnInit only one time in a nested component

I have two components: CreateComment and DisplayComment. DisplayComment component has itself nested in it for displaying the threaded comments.

Now, whenever I create a comment from CreateComment component, I call a subject in CommentService to emit an event. This subject is being subscribed in the DisplayComment component in which I am pushing the comment to the comments array to be rendered.

Since I have nested components, this subscription is being called multiple times (according to the threaded comments count).

Can someone please let me know if there is any way I can restrict the subscription execution on the DisplayComment method to only one time?

If you need a subscription to complete on a certain amount of emissions, you could look into RxJS take operator.

ngOnInit() {
  this.someService.someObservable.pipe(
    take(1)
  ).subscribe(
    response => {
      // do something
    }
  );
}

You could also increase the argument to the number of values you wish to be emitted before the subscription completes. For take(1) the subscription will complete after one value is emitted.

There is also a RxJS first() operator. See here for the differences between take(1) and first() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM