3 times better way of calling API with Angular

Recently I worked on an Angular project where stuff like calling API with Angular app needs to be done, pretty basic I guess. But if you used to Google it before starting off, just like me, you will find hundreds of articles explaining how you can set up calling API with Angular. Definitely follow those articles and get one prototype ready. It will help you build this unique way, what we will be discussing in this post, a lot.

Before we dig in, I want you to have the basic knowledge of the Angular framework so that you will better understand why some of the steps are needed to perform. But Still, if you just follow the steps with me you will get your “calling API with Angular” up and running.

Why upgrade calling API with Angular?

So, before coding anything if you are used to Google that like me, then definitely you will find many solutions to implementing Service Calling in Angular. I did the same but when I solutions I found that most of the developers used to create dedicated services for each component.

But recently I went through a Github repo and discovered a stunning idea of writing script. Let’s discuss that thing.

I found that calling api with angular is a rather very easy thing, but with the growing application, this might get complex and hard to manage. Because we write services for each api call.

Read More: The unusual pandemic activity is confounding AI models

Solution

What if, we make just one service and make calling API with Angular. It will make our service simple and compact moreover robust for api calls.

Step 1

Create a new Angular App.

ng your-angular-app

Step 2

Create one and only service to perform API calls. Create a new service with the following command. Also, you can go through the official documentation once.

ng g s Api

Step 3

Now let’s modify the service file like this.

import { Injectable } from '@angular/core';
import { endpoints } from './endpoints';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { environment } from 'src/environments/environment';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  constructor(private http: HttpClient) { }
  public request(key, payload?) {
    const GetBaseURL = () => {
      let HTTP_PROTOCOL = environment.HTTP_PROTOCOL
      let HTTP_PORT = environment.HTTP_PORT
      let HTTP_HOST_NAME = environment.HTTP_HOST_NAME
      let API_VERSION = environment.API_VERSION
      return HTTP_PROTOCOL + '://' + HTTP_HOST_NAME + ':' + HTTP_PORT + '/' + API_VERSION
    }
    let header = new HttpHeaders();
    header = header.append('Content-Type', 'application/json');
    if (endpoints.request[key].hasOwnProperty('header')) {
      if (endpoints.request[key].header['ContentType']) {
        header = header.set('Content-Type', endpoints.request[key].header['ContentType']);
        if (endpoints.request[key].header['ContentType'] === 'application/x-www-form-urlencoded') {
          if (payload) {
            let form_data = new HttpParams({
              fromObject: payload
            });
            payload = form_data
          }
        }
      }
    }
    if (endpoints.request[key].hasOwnProperty('token') ? endpoints.request[key].token.is_needed : undefined) {
      header = header.append(
        'Authorization',
        Capitalize(endpoints.request[key].token.type) + ' ' +
        this.getToken(endpoints.request[key].token.type)
      )
    }
    if (endpoints.request[key].method == 'get') {
      if (!payload) payload = ''
      return this.http.get(GetBaseURL() + endpoints.request[key].url + payload, { headers: header })
    }
    if (endpoints.request[key].method == 'post') {
      return this.http.post(GetBaseURL() + endpoints.request[key].url, payload, { headers: header })
    }
    if (endpoints.request[key].method == 'put') {
      return this.http.put(GetBaseURL() + endpoints.request[key].url, payload, { headers: header })
    }
  }
  public setToken(data) {
    sessionStorage.setItem('access_token', data.access_token);
    sessionStorage.setItem('refresh_token', data.refresh_token);
  }
  public getToken(type = 'Bearer') {
    if (type === 'Bearer') {
      return sessionStorage.access_token
    } else if (type === 'Basic') {
      return environment.BASIC_TOKEN
    }
  }
  public deleteToken(data) {
    sessionStorage.removeItem('token');
  }
}
const Capitalize = (s?) => {
  if (typeof s !== 'string') return undefined
  s = s.toLowerCase()
  return s.charAt(0).toUpperCase() + s.slice(1)
}

Step 4

Now, we have finished the heart of the service. Let’s add the API routes. For that create a new file endpoints.ts.

 
import { environment } from 'src/environments/environment'

export const endpoints = {
    request: {
        GetAuthToken: {
            method: 'post',
            url: '/oauth/token',
            token: {
                is_needed: true,
                type: 'Basic'
            },
            header: {
                'ContentType': 'application/x-www-form-urlencoded'
            }
        },
        Register:{
            method: 'post',
            url: '/register',
            token: {
                is_needed: true,
                type: 'Basic'
            }
        }
    }
}

Step 5

It is a good practice to save our API’s base URL in the environment file. For that go to,

src > environments > environment.ts

Now update the file such as,

export const environment = {
  production: false,
  HTTP_PROTOCOL: 'http',
  HTTP_PORT: '8000',
  HTTP_HOST_NAME: 'localhost',
  API_VERSION: 'v1',
  BASIC_TOKEN: '<BASIC_TOKEN>'
};

Read More: Loon’s balloon-powered internet

Step 6

Make sure you import the HttpClientModule in the app module, i.e. app.module.ts. This will look something like this.

 
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,  // <<- Added HttpClientModule Module
    AppRoutingModule,
  ],
  providers: [
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

 

That’s it. Now compile your Angular App with

ng serve

Hope this will run the app smoothly.

Now how to use it?

To use this service you need to create components or let’s just use the app’s default component i.e. app.component.ts. And Update to file as bellow,

import { Component, OnInit } from '@angular/core';
import { ApiService } from 'src/app/shared/services/api.service';

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

  constructor(
    private api: ApiService // <<- Dependancy Injection
  ) { }

  ngOnInit(): void {
     this.api.request('GetAuthToken', payload).subscribe(
      (data) => {
       console.log(data);
      },
      (error) => {
        console.log(error);
      }
    )
  }
}

 

This’s all. You just finished setting up your “Better way of calling API with Angular”.

I hope this will help you. If it did please like & share this post. And feel free to discuss any doubt you have or any suggestions you want to give me in the comment section below. I will be happy to hear from you.

2 COMMENTS

  1. […] 3 times better way of calling API with Angular […]

Leave a Reply