Home > other >  Subscription to subject not firing when value changes
Subscription to subject not firing when value changes

Time:07-05

I have a component that calls a REST api to get some infos. When this infos are ready, I need another component to use them. These components are siblings. To implement this, I'm using a service and subject.next to update the value. The other component needs to listen to changes. This is what I'm doing:

Component A:

    this.restService.getInfos().subscribe(i => {
        this.updatingService.profileLoadedEvent(i)
    });

Updating service:

    userInfo = new Subject<any>();
    
    public profileLoadedEvent(info: string) {
            this.userInfo.next(info);
    }

    public getProfileLoadedEvent(): Observable<string> {
        return this.userInfo.asObservable();

    }

Component B:

    this.updatingService.getProfileLoadedEvent().subscribe((info: string) => {
      this.doSomething(info);
    })

My problem is that component B never gets to doSomething(). Component A correctly calls userInfo.next but the

    return this.userInfo.asObservable();

is not called. Well, it's called only once before the profileLoadedEvent method is called by component A.
What am I doing wrong?

CodePudding user response:

Your service is creating a new observable every time it calls the function, depending on the timing of sending something and the function call to get the Observable you will not receive anything. You can change it to:

@Injectable({
  providedIn: 'root'
})
export class updatingService {

  private: userInfo = new Subject<any>();
  userInfo$ = this.userInfo.asObservable();

  public profileLoadedEvent(info: string) {
        this.userInfo.next(info);
  }

  public getProfileLoadedEvent(): Observable<string> {
    return this.userInfo$;
  }
}

CodePudding user response:

Try to use BehaviorSubject instead of Subject, I solved the same problem is this way.

import { BehaviorSubject } from 'rxjs';


userInfo: BehaviorSubject<any> = new BehaviorSubject({});

getUserInfo() {
  return this.userInfo.asObservable();
}

Component:

this.restService.getUserInfo().subscribe((info:any) => {
   this.doSomething(info);
});

Check this link to unterstand BehaviorSubject vs Observable?

  • Related