Call Rest API, Web services using Angular and RxJS.

Call Rest API, Web services using Angular and RxJS.

Call and cache data returned from HttpClient. Caching data will speed up your web/app. Let's understand how..!

HttpClient returned an observable. To cache we need to combine that observable with shareReplay and catchError. We use caching to avoid too many request to server.

Let's dive into the details of HTTP API calls:

#1) Without using Caching.
#2) With Caching values.
#3) With Caching Observable.


Before Calling APIs

You must have APIs, follow this article to create APIs using Node.js and Express.js: Link to Create Rest API👆

#1) API calls without using Caching.

Now suppose we have API endpoint which return list of items - each item is a JSON object.
API end-point: localhost:3000/items (Returns list of objects, see image below👇) (To create API follow: Link to Create Rest API👆)

Let's create a Service for our Items as follows:
We'll write code in this service file which returns list of items.
(make sure within your project root directory run below command👇)

ng g service service/items

This command will generate two TypeScript file – look below👇

Next, open the src/app/service/items.service.ts file and update code:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ItemsService {

  // URL which returns list of JSON items (API end-point URL)
  private readonly URL = 'http://localhost:3000/items';

  constructor(private http: HttpClient) { }

  // create a method named: resolveItems()
  // this method returns list-of-items in form of Observable
  // every HTTTP call returns Observable object
  resolveItems(): Observable<any> {
    console.log('Request is sent!');
    // this.http is a HttpClient library provide by @angular/common
    // we are calling .get() method over this.http object
    // this .get() method takes URL to call API
    return this.http.get(this.URL);
  }
}

Next we will test this API in the Component. For that we will use method we created in items.service.ts.

Let's create a Component for our Items as follows:
(make sure within your project root directory run below command)

ng g component items

This command will generate four TypeScript file – look below👇

Important

Do not forget to do Routing of this new ItemsComponent.
Two steps to do that:
#1. Define your component route in app-routing.module.ts file.
#2. Declare your component in app.module.ts file.

Let's do this...

#1. Open up your src/app/app-routing.module.ts file and update it as follows:

...

import { ItemsComponent } from './items/items.component';

const routes: Routes = [
  ...
  {
    path: 'items',
    component: ItemsComponent
  }
];

...

#2. Open up your src/app/app.module.ts file and update it as follows:

...

import { ItemsComponent } from './items/items.component';

@NgModule({
  declarations: [
    AppComponent,
    ItemsComponent
  ],
  ...
})

...

Learn more in depth about 'Routing of an Angular Component'
(Click here👆)


Finally, open the src/app/items/items.component.ts file and update it as follows:

import { Component, OnInit, Input } from '@angular/core';
import { Observable } from 'rxjs';
import { ItemsService } from '../service/items.service';

@Component({
  selector: 'app-items',
  templateUrl: './items.component.html',
  styleUrls: ['./items.component.scss'],
})
export class ItemsComponent implements OnInit {

  @Input()
  result$: Observable<any>;

  constructor(private itemsService: ItemsService) {
    this.result$ = itemsService.resolveItems();
  }

  ngOnInit() {}

}

Next, open the src/app/items/items.component.html file and update it as follows:

<pre *ngIf="code">
  {{(result$|async)|json}}
</pre>

Now, let’s use our ItemsComponent in the AppComponent. Open the src/app/app.component.html file and add this code:

<!-- This tag is a selector of src/app/items/items.component.ts file to be added anywhere in src/app/app.component.html file -->
<app-items></app-items>

Done 🤩
The output of the code is here👇👇 The data is loaded in form of JSON object.


Conclusion

We have seen HTTP API calls with following ways:
#1) Without using Caching.
#2) With Caching values.
#3) With Caching Observable.


Done! 🤩 It’s that simple to Call Rest API/Web services using Angular and RxJS.

See you later 👋👋


Feel free to comment down in the comment box… If I missed anything or anything is incorrect or anything does not works for you :)
Stay connected for more articles.