0
votes

I have a Subject in my Angular Service like this:

private sub = new Subject();


sendSub(page: page) {
    this.sub.next(page);
}

getSub(): Observable<any> {
    return this.sub.asObservable();
}

In my parent component I have subscribed to getSub(). From my child component I'm sending one next value but in the parent I'm getting two values in subscription.

Need only one value so that my code block executes only once:

subscription: Subscription;

this.subscription = this.pageService
    .getSub()
    .subscribe(
        (data) => {
            this.data = data;
            this.nextSelection();
        }
    );
2
Where do you call this.pageService.getSub().subscribe()? Provide some context.frido
@fridoo The call is in the parent constructor blockprabas
Your parent component might be created twice. Put a console.log in the constructor to check if it's executed twice.frido
getSub() is called only once in the application and this is the only instance that consumes the data from the subject. @fridooprabas
Well, if the subscribe next callback is executed twice there can be two reasons for that. Either you subscribe once and the subject emits twice or you subscribe twice and the subject emits once. Do you ever unsubscribe?frido

2 Answers

0
votes

Change

getSub(): Observable<any> {
  return this.sub.asObservable();
} 

to

getSub: Observable<any> = this.sub.asObservable();

This ensures that every subscriber uses the same subject.

0
votes

Add Subscribe code in the constructor of the parent component.Here is a fiddle of the same

this.appService
    .getSub()
    .subscribe(
        (data) => {
             this.data = data;
             this.nextSelection();
        }
    );