Gee Varghese
Gee Varghese

Reputation: 1

Angular subscribe in looped children called multiple times

I have a ParentComponent which has a *ngFor loop to add ChildComponent. The ChildComponent has a ButtonComponent which has a button when clicked updates a variable in a BehaviourSubject.

The ngOnInit() of the ChildComponent subscribes to the BehaviourSubject. I expect it to be subscribed only once. But what happens is, if there are 50 ChildComponents, the subscription happens 50 times.

Any help is highly appreciated.

ParentComponent html

<div class="parent">
  <div *ngFor="let c in count">
    <child-component></child-componet>
  </div>
</div>

ParentComponent ts

count = [1, 2, 3];

ChildComponent html

<div class="child">
  <buttons-component></buttons-component>
</div>

ChildComponent ts

ngOnInit(): void {
  this.service.yourName
    .pipe(distinctUntilChanged(),take(1))
    .subscribe((x) => {
      console.log("hello");
    });
}

ButtonsComponent html

<div class="button">
  <button (click)="change()">Click</button>
</div>

ButtonComponent ts

change(): void {
  this.service.changeName("somename");
}

Service file

private source = new BehaviorSubject<string>(null);
yourNAme = this.source.asObservable();
    
changeName(message: string) {
  this.source.next(message);
}

Upvotes: 0

Views: 429

Answers (1)

shubham
shubham

Reputation: 11

You are subscribing in the ngOnInit of child component, so there are 50 subscribes if there are 50 child.

Instead subscribe in the parent component so you only subscribe once.

Put the following in Parent Component instead of Child Component

ngOnInit(): void {
    this.service.yourName
      .pipe(distinctUntilChanged(),take(1))
      .subscribe((x) => {
        console.log("hello");
      });
   }

Upvotes: 1

Related Questions