I have an HTTP call in Angular that returns a promise. I am using setTimeout to refresh the call after an interval. Is it possible to use some inbuilt functions / patterns that can do the job?
1 Answer
Yes you can use RXJS too easily. But without using Promises ofcourse, and here comes the power of rxjs in its so powerful operators like interval.
interval(1000)
.pipe(
switchMap(() => this.http.get('...url...')),
map(response => {
if(response.statusCode == 1) return response.data;
else return undefined; //or some error message or data.
})
)
.subscribe(response => {
// do somthing with the response that will come in one second interval
});
Basically it looks something like this. But if you provide you own code we can help you transfer to work exactly as you want using only rxjs. which is really powerful library built upon the very good Observable Design Pattern.
6 Comments
awesomemypro
How do we get out of this depending on a condition checked on the response?
Louay Al-osh
we can use the
map operator with a condition then. I'll update the answer for you.awesomemypro
I did not understand the "breaking out" part. Can you elaborate a bit more?
awesomemypro
Also, I'm getting this: Property 'pipe' does not exist on type 'Observable<number>'
Louay Al-osh
@awesomemypro which version of RXJS are you using? because older version need a bit different syntax, and the idea behind map operator here is to switch your pipeline return value based on some condition you want.. keep in mind if you are only want one condition to hold true you can use the
filter operator.. check that out. |