Monday, August 19, 2019

Angular CLI - How to cache Http Service calls simply using rxjs

To cache simply in Angular 7 CLI, here used rxjs on HttpClient.

To cache entire country list, we can use as follows,


import { map, catchError, shareReplay } from 'rxjs/operators';
import { throwError, Observable } from 'rxjs';

private countryCache$ = Observable<any>;
  getCountryList() {
    if (!this.countryCache$) {
      this.countryCache$ =
        this.http.get('/api/country/getCountryList')
          .pipe(
            map(response => {
              return response;
            }),
            catchError((error, caught) => {
              return throwError(error);
            }),
            shareReplay(1)
          );

    }
    return this.countryCache$;
  }



To cache object by it's parameter we can use as follows,in this example cached country information by it's name.

private countryInfoCache$ = new Map<string, Observable<any>>();
getCountryInfo(countryName: string) {

    if (!this.countryInfoCache$.get(countryName)) {

      let countryInfoCacheResult =
        this.http.get('/api/country/getCountryInfoByName',
          { 'countryName': countryName })
          .pipe(
            map(response => {
              return response;
            }),
            catchError((error, caught) => {
              return throwError(error);
            }),
            shareReplay(1)
          );

      this.countryInfoCache$.set(countryName, countryInfoCacheResult);
    }
    return this.countryInfoCache$.get(countryName);

  }

Wednesday, August 7, 2019

Angular CLI - How to use async and await

In Angular Cli, we can use async and await to perform service calls to wait for the promise. Usually we do call first service and then in subscribe method we do perform other logics. But now we can use toPromise method with asyn/await to perform the same as below,

Existing approach:


saveMethod(){
this.someService.getFirstResult().subscribe((data) ={
//second service depend on first service data
this.someService.getSecondResult(data.id).subscribe((data2) => {
        //Do perform your business logics here..
});
});
}


Aysnc/Await approach:

async saveMethod(){
let data = await this.someService.getFirstResult().toPromise();
//second service depend on first service data
let data2 = await this.someService.getSecondResult(data.id).toPromise();
//Do perform your business logics here..
}