1

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 1

2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

How do we get out of this depending on a condition checked on the response?
we can use the map operator with a condition then. I'll update the answer for you.
I did not understand the "breaking out" part. Can you elaborate a bit more?
Also, I'm getting this: Property 'pipe' does not exist on type 'Observable<number>'
@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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.