I set up a service to make an http Request.
private readonly changeSelectedId$ = new Subject<string>();
private readonly selectedId$ = this.changeSelectedId$.pipe(
distinctUntilChanged(),
untilDestroyed(this),
switchMap((id) => this.httpClient.get<AuthenticatedSubject>(`${this.endpointService.get()}/${id}`)),
catchError((e) => {
return EMPTY;
})
);
public getNewData(newId: string): Observable<AuthenticatedSubject> {
this.changeSelectedId$.next(newId);
return this.selectedId$;
}
In my component i listen for emission from a formControl
and i use switchMap
operator to call the service and, at last, i subscribe to get the result:
ngOnInit(): void {
this.formControl.valueChanges.pipe(
untilDestroyed(this),
switchMap(newId=> this.loginDataAccessService.getNewData(newId)))
.subscribe(authData => console.log(authData))
}
The problem is that, if I initialize changeSelectedId
as Subject
, it doesn't work. Instead, using ReplaySubject
, it works as expected and i get the value in the console. I know the difference between Subject
and ReplaySubject
, but it's not clear why, using Subject
, it doesn't work. Thanks to who will answer me.