Back Copy 3 back
image

How to track your API calls status progress using rxjs and ngx-ready-set-go lib for Angular

Web Factory August 29, 2020
share this on
Spinner: failed to spin, spinning and done

I am working on a project at the moment where we needed to develop an admin panel from scratch in Angular 9 (soon after we updated it to Angular 10). Because there are a lot of CRUD operations like views, lists, items, new, edit, bla bla bla… you know what I mean, there are a lot of progress indicators as well.

For example in my case, I had “create new item component” where I needed to populate multiple select elements with data before I was able to select “Create”. This means I had to track the loading/error/loaded progress on all of them. Same goes for the “edit” of that item, but additionally in “edit” to load the item’s latest data from the API. Again, you get my point. A lot, a lot of indicators to keep track of. True, false, true, false and etc.

So, I am using rxjs and I created something that I call “ready, set and go”. It’s a simple indicator that you can pipe to your observables. It tracks the loading, loaded and error state when you subscribe. This way you will avoid to keep track and manually set the boring booleans. In the same time you will have more time to see some memes online :). Kidding, just keep coding.

What I did is the following:

TS code

  • Create your indicator
indicator: IndicatorBehaviorSubject = new IndicatorBehaviorSubject();
  • Pipe it to the request
this.readySetGoService.getUsersFromAPI()
.pipe(indicate(this.indicator))
.subscribe((res: any) => {
   console.log(res);    
});

HTML

  • Use it in your HTML
<div *ngIf="indicator | async as status">      
  <span>Loading: {{status.loading}}</span>      
  <span>Error: {{status.error}}</span>      
  <span>Loaded: {{status.loaded}}</span>    
</div>

 

Helper Service

  • My service looks like this (using some json placeholder service)
getUsersFromAPI(): Observable<any> {
return this.httpClient.get(`https://jsonplaceholder.typicode.com/todos/1`)
.pipe(map((response: any) => {      
   return response;    
}));

I hope this will solve your problems as it did for mine. Have fun!

I am happy to hear your comments, feedbacks and suggestions.

You can find the lib herehttps://www.npmjs.com/package/ngx-ready-set-go

GitHub repo herehttps://github.com/webfactorymk/ready-set-go/tree/master/projects/ngx-ready-set-go

There are guidelines about how to use the lib in the ReadMe file.

https://github.com/webfactorymk/ready-set-go/blob/master/projects/ngx-ready-set-go/src/lib/ngx-ready-set-go.ts