In my Angular component, I am working with the following code:
@Component({...})
export class ComponentOne implements OnDestroy, OnChanges {
readonly myBehaviourSub = new BehaviorSubject<Observable<MY_CUSTOM_INTERFACE>>(NEVER);
constructor(private readonly myService: MyService){}
ngOnChanges(changes: SimpleChanges) {
this.myBehaviourSub.next(
this.myService.fetchSomeData(alpha, beta, gamma)// 'fetchSomeData' returns an observable with type MY_CUSTOM_INTERFACE
.pipe(
shareReplay({refCount: true, bufferSize: 1})
)
);
}
}
The structure of MyService resembles this:
@Injectable({providedIn: 'root'})
export class MyService {
fetchSomeData(alpha, beta, gamma) : Observable<MY_CUSTOM_INTERFACE> {
...
return obs<MY_CUSTOM_INTERFACE>;
}
fetchNewValuesForAlpha() : Observable<ALPHA_INTERFACE> {
...
return obs<ALPHA_INTERFACE>
}
}
I have a requirement to retrieve new values for "alpha" by first calling "fetchNewValuesForAlpha" before passing it to "fetchSomeData". Here is what I attempted:
@Component({...})
export class ComponentOne implements OnDestroy, OnChanges {
readonly myBehaviourSub = new BehaviorSubject<Observable<MY_CUSTOM_INTERFACE>>(NEVER);
constructor(private readonly myService: MyService){}
ngOnChanges(changes: SimpleChanges) {
this.myBehaviourSub.next(
this.myService.fetchNewValuesForAlpha()
.pipe(
switchMap(response => response.newValue))
.subscribe(
(newAlpha) => this.myService.fetchSomeData(newAlpha, beta, gamma)
.pipe(shareReplay({refCount: true, bufferSize: 1})
);
);
}
}
However, I encountered an error because "fetchNewValuesForAlpha" returns an observable. Despite trying to use switchMap to resolve this issue, I faced the following error message:
Argument of type 'Subscription' is not assignable to parameter of type 'Observable<MY_CUSTOM_INTERFACE>'