Call RESTful APIs | 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…

Call RESTful APIs | 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! image HttpClient returned an observable. To cache, we need to combine that observable with shareReplay and catchError. We use caching to avoid too many requests to the 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 an API endpoint which returns a 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👆) image Let’s create a Service for our Items as follows: We’ll write code in this service file which returns a 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👇 image Next, open the src/app/service/items.service.ts file and update code:

Using HTTP GET method:
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);
  }
}
Using HTTP POST method:
import { Injectable } from '[@angular/core](http://twitter.com/angular/core)';
import { HttpClient } from '[@angular/common](http://twitter.com/angular/common)/http';
import { Observable } from 'rxjs';[@Injectable](http://twitter.com/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!');
    // Using the POST method
    const headers =  {
      headers: new  HttpHeaders({
        'Content-Type': 'application/x-www-form-urlencoded'})
    };
    return this.http.post(this.URL,
    {
      'email' : '[ankit.codechintan@gmail.com](mailto:ankit.codechintan@gmail.com)',
      'phone' : 910950xxxxx
    },
    headers)
  }
}

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👇 image

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. image

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 👋👋

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics