Dealing with API based token is sometimes cumbersome. Due to the fact that, on every request, we have to send a token as parameter to be able to reach out the server.

In Angular, it becomes easier with the help of HttpClient interceptors. In this tutorial, i will lead on how to set up a token once and use it on every request with interceptors.

Sorry for the interrupt!

If you’re interested in learning Angular in a comprehensive way, I highly recommend this bestseller course: Angular - The Complete Guide (2020 Edition)

It’s an affiliate link, so by purchasing, you support the blog at the same time.

Prerequisites

Set up a new angular app

ng new my-app

Then add a service file that will handle the logic of sending the request.

ng generate service data

After successfully generated the service add the following lines to send the request to the server.

import { Injectable } from "@angular/core";
import { HttpClient, HttpParams } from "@angular/common/http";

@Injectable({
  providedIn: "root"
})
export class DataService {
  constructor(private http: HttpClient) {}

  getData() {
    return this.http.get("https://example.com/api/data", {
      params: new HttpParams().set(
        "auth-token",
        "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9"
      )
    });
  }

  getUsers() {
    return this.http.get("https://example.com/api/users", {
      params: new HttpParams().set(
        "auth-token",
        "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9"
      )
    });
  }
}

#angular #angular 8 #api

Better Http request with interceptors in Angular 8 and beyond
1.20 GEEK