Utilizing Ionic Storage to set default request headers through an HTTP interceptor in an Angular 5 and Ionic 3 application

I'm attempting to assign a token value to all request headers using the new angular 5 HTTP client. Take a look at my code snippet:

import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import {Observable} from "rxjs/Observable";
import { Storage } from '@ionic/storage';
import {Globals} from '../globals/globals';

@Injectable()
export class Interceptor implements HttpInterceptor {
  token: string;
  constructor(private storage: Storage, private global: Globals){ 
    this.storage.get('token').then((val) => {
      this.token = val;
    });
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log(this.token) //undefined "only for first time on app start"
    req = req.clone({
      setHeaders: {
        'Token': this.token,
        'Version': this.global.version,
      }
    });
    return next.handle(req);
  }
}

Although adding the token to the request header works, there is a minor issue. It does not work initially. This occurs due to the asynchronous nature of JavaScript, where req.clone gets executed before retrieving the token from storage. As Ionic storage returns a promise, how can one handle this situation for the initial run?

Answer №1

You have the option to combine both async requests (obtaining the token and processing the request) to carry out the latter when the token is available, as opposed to retrieving it in the constructor:

// -------------------------------------------------------------------------
// Keep in mind that I am utilizing lettable/pipeable operators (RxJS > 5.5.x)
// https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md
// -------------------------------------------------------------------------

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from "rxjs/Observable";
import { Storage } from '@ionic/storage';
import { Globals } from '../globals/globals';

// New additions!
import { fromPromise } from 'rxjs/observable/fromPromise';
import { mergeMap } from 'rxjs/operators/mergeMap';

@Injectable()
export class Interceptor implements HttpInterceptor {

  constructor(private storage: Storage, private global: Globals){ }

  getToken(): Promise<any> {
    return this.storage.get('token');
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return fromPromise(this.getToken()).pipe(
        mergeMap(token => {

            // Incorporate the token into the request
            req = req.clone({
                setHeaders: {
                    'Token': token,
                    'Version': this.global.version,
                }
            });

            // Process the request
            return next.handle(req);
        }));
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The table refuses to load

I've been troubleshooting this issue for the past two days. The array is visible in the console, but it refuses to show up on the table. I've tried multiple approaches, but none seem to work. I suspect that "tobodyHtml" is not defined properly, a ...

Iterate through the JSON response and send it back to Jquery

I'm almost done with my first jQuery autocomplete script and just need some assistance in understanding how to make the found elements clickable as links. Here is a snippet of my JavaScript code: $(document).ready(function() { var attr = $(&apos ...

Harness the power of Angular 2 on standard shared hosting services

Starting with AngularJS 2: Installed NodeJS Downloaded the initial project Ran it on Node Everything works perfectly! But now, how can I run it in a production environment on shared hosting (without Node and not on a VPS)? How can I open it in a browse ...

The enigmatic dance of Angular and its hidden passcodes

Recently, I've been diving into learning Angular 2 and I'm exploring ways to safeguard the data in my application. I'm curious about how one can prevent data from being accessed on the front end of the app. Could serving the angular app thr ...

Enhancing Skylinkjs functionality using Typescript

Hello fellow developers, I am new to using typescript and currently experimenting with incorporating SkylinkJS into my project. Can anyone guide me on the best practices for utilizing an npm library with TypeScript? If you are interested in checking out t ...

Encountering an error message saying "assignment to undeclared variable"

I'm attempting to incorporate a react icon picker from material-ui-icon-picker However, I keep encountering an error stating "assignment to undeclared variable showPickedIcon" edit( { attributes, className, focus, setAttributes, setFocus, setState ...

Caution when using a React form: Value of `true` has been detected for a non-boolean attribute `validate`

I am trying to address a warning message that I have received index.js:1 Warning: Received true for a non-boolean attribute validate. If you want to write it to the DOM, pass a string instead: validate="true" or validate={value.toString()}. I ...

Angular Reacts to Pre-Flight Inquiry

I'm facing an issue with my interceptor that manages requests on my controllers. The back-end web API has a refresh token implementation, but when I try to refresh my token and proceed with the request, I encounter the error message "Response to prefl ...

Webpack generates unique hashed file names for images within the project

Within one of the components located in my client/components directory, I have imported three images from the public/images folder. Recently, webpack generated hashed files for each image such as: 0e8f1e62f0fe5b5e6d78b2d9f4116311.png. Even after deleting t ...

What is the best way to retrieve the scope of ng-repeat from another directive located on the same element as ng-repeat?

Is it possible to access a property from the ng-repeat scope in another directive within the same element as the ng-repeat directive? For instance, I would like to be able to use the child.class property in this scenario: <div ng-class="{{ child.class ...

What is the method for accessing extra parameters in the signIn() callback function in [...nextauth]?

As per the Next Auth documentation, it is possible to pass extra parameters to the /authorize endpoint using the third argument of signIn(). The examples provided are: signIn("identity-server4", null, { prompt: "login" }) // always ask ...

Updating a behavior object array in Angular 5 by appending data to the end

After creating a service to share data across my entire application, I'm wondering if it's possible to append new data to an array within the userDataSource. Here is how the service looks: user.service userDataSource = BehaviorSubject<Array& ...

Tips on incorporating a dynamic variable value as a class name within a span tag

I am a beginner in the world of JavaScript. Below is the code snippet I am working with: result.push(`<span class="mark">${str.substring(h.startOffset, h.endOffset)}</span>`); Currently, I have a variable called var className = "dynamicvalue" ...

Trouble with embedding video in the background using Next.js and Tailwind CSS

This is the code snippet for app/page.tsx: export default function Home() { return ( <> <main className='min-h-screen'> <video muted loop autoPlay className="fixed -top ...

Exploring the possibilities with Rollbar and TypeScript

Struggling with Rollbar and TypeScript, their documentation is about as clear as AWS's. I'm in the process of creating a reusable package based on Rollbar, utilizing the latest TS version (currently 4.2.4). Let's delve into some code snipp ...

Angular 9 introduces a new feature where canActivate now supports Observable<boolean> which provides a more robust error handling mechanism for failed

Currently, I am working with angular9 and rxjs6 while implementing canActivate: Observable feature. However, I encountered an error when attempting to use catchError, as shown in the image below: Is there a solution to fix this issue? I have already tried ...

"Troubleshooting asynchronous requests in Angular and the issue with Http.get method

I have encountered an issue with my code while trying to make a http request to obtain the client's geoLocation and sending it to my API using http.get as a parameter. Although I have successfully implemented both functionalities, I am facing challeng ...

How to retrieve the data variable in Vue JS script

I recently started using vue.js and I'm working with version 2.5.13. In my component file script, I am trying to access a data variable but it keeps returning as undefined. The id attribute in the component is displaying the correct value, however w ...

Is it possible for me to utilize pure JavaScript for loading JSON data?

I am interested in dynamically creating a Google Map by loading data through AJAX. To achieve this, I am using a JSON object that mimics the structure of the GM API to construct the map and jQuery for AJAX loading. For example: "object": { "div": "ma ...

Is it possible for a React application to manage errors (status code 4xx) using a try-catch block

Currently delving into React (using hooks) and facing an interesting challenge. I am in the process of building a Notes Application (from FullStackOpen's learn react section). The database I'm working with only allows notes with content length gr ...