Making first observable in chain optional
Making first observable in chain optional
I currently have two API requests, where the first feeds into the second:
.get('/call1', )
.pipe(
switchMap(response => {
this.api.get('/call2', )
This works fine (though if there's a more appropriate way of doing it, I'd love to hear!). However, with some recent changes to my app, I realize in certain cases I have the data that call1
gets already stored, and thus can go straight to the second call, but I can't figure out how to do that. In other cases, within a switchMap
, I've done something like:
call1
switchMap
if (condition)
return this.api.get('/call2');
else
return ObservableOf(cachedData);
How can I do something similar for the first call in a chain?
this.api.get('...').subscribe( (result) => whatever you want)
From everything I've read/seen, it's really bad form to call an observable from within an observable? That's the point of maps.
– RhoVisions
Aug 22 at 15:39
2 Answers
2
You can apply the condition in a separate function
getCall1()
.pipe(
switchMap(response => {
this.api.get('/call2', )
The function can decide where to get the data from and return an observable just like your example:
getCall1() : Observable<any>
if (condition)
return this.api.get('/call2');
else
return of(cachedData);
I'd recommend using some kind of caching layer or data store in your API layer. That way every time you call "this.api.get()" you can return an observable with the appropriate value if it's already been retrieved. We use the latest version of angular and do something similar while saving the values after API calls locally using the browsers local storage.
It does have caching, but in this instance, the data may not be coming from my api, so doesn't work out.
– RhoVisions
Aug 23 at 20:29
I didn't mean caching on the API side, but on the client side similarly to what tom had suggested above.
– HeWhoFreeks
Aug 24 at 0:38
I am caching client side, but the data doesn't always come from the API, thus why I need to pick from different sources.
– RhoVisions
Aug 24 at 18:41
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
why not just subscribe ...
this.api.get('...').subscribe( (result) => whatever you want)
– Stavm
Aug 22 at 13:44