Navigating through a mergeMap observable with an undefined value

In my Angular 6 app, I have a class that attaches API tokens to every http request using the getIdToken() method. If the token retrieval is successful, everything works fine. However, if it fails, my app will stop functioning.

I need help with handling the mergeMap function when getToken fails. Any suggestions?

I'm struggling with managing the mergeMap observable function in this scenario.

Below is the code snippet of my class :

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse,
    HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/empty';
import 'rxjs/add/operator/retry';
import 'rxjs/add/operator/mergeMap';
import { of } from 'rxjs';


import { UserService } from '../user/user.service';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

    private token;

    constructor(private userService: UserService) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return this.userService.getToken().mergeMap(
            (token) => {
                request = request.clone({ headers: request.headers.set('Authorization', token) });
                return next.handle(request);
            }
        );
    }
}

These are the getToken functions from userService class:

  public async getIdToken() {
    if (this.getCurrentUser() !== null) {
      try {
        const session = await this.getCurrentUserSession();
        return session.getIdToken().getJwtToken();
      } catch (err) {
        return Promise.reject(err);
      }
    } else {
      return Promise.reject('No Current User');
    }
  }

  public getToken(): Observable<any> {
    return Observable.fromPromise(this.getIdToken());
  }

Answer №1

If you want to improve your code, consider inserting a catch statement right before your mergeMap method:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return this.userService.getToken()
        .catch(error => // handle error here)
        .mergeMap(
            (token) => {
                request = request.clone({ headers: request.headers.set('Authorization', token) });
                return next.handle(request);
            }
        );
}

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

Utilizing inline javascript to dynamically update the selected option of a radio button

A form on my website includes two radio buttons: one labeled 'trigger_unit' and the other labeled 'normal_unit'. In addition, there is a select drop-down menu with four values and a default NULL option. <select rel="dropdown" name=" ...

Tips for showing multiple autocomplete entries in a text box following a successful AJAX request

I'm having an issue with my code where the autocomplete multiple values, successfully retrieved by Ajax, are not being displayed. Here is the HTML I am using for display: <input type="text" name="s_to" id="s_to" class="controls"> Here is my jQ ...

Creating a direct connection between a parent node and all of its children in OrgChartjs

Can I connect all children directly to one parent in Balkan OrgChart.js? This is my starting point based on the documentation of OrgChart.js. window.onload = function () { OrgChart.templates.family_template = Object.assign({}, OrgChart.templates.ana); ...

Having trouble getting anime.js to function properly in an Ionic 3 project?

I have been attempting to incorporate anime.js into my Ionic 3 project, but I keep encountering an error when using the function anime({}) in the .ts file. Error: Uncaught (in promise): TypeError: __webpack_require__.i(...) is not a function TypeError: _ ...

No instances are returned by Processing.instances

I am experiencing an issue with a webpage that is running 2 processing sketches. I came across a suggestion to call Processing.instances[0].exit() in response to a question on dynamically unloading a Processing JS sketch from canvas. However, when I attem ...

What is the method for adjusting the time format?

Using the TIME data type, my data is currently displayed in the format hh:mm:ss (03:14:00). How can I change it to display in the format hh:mm (03:14)? The usual DATE type method does not seem to work: {{test.time | date: 'HH:mm'}} However, thi ...

Arranging based on attribute data

I'm currently working on organizing a collection of divs that have unique custom data attributes which I aim to sort based on user selection. For instance, if 'followers' is chosen, the .box elements will be arranged according to their data- ...

What is the best way to integrate and utilize the jsgrid library in a React project?

I've encountered an issue with the jsgrid library while trying to integrate it into a React project. I followed the instructions on npmjs and included the necessary libraries in the project. Here is my code snippet: index.html <!DOCTYPE html> ...

"Key challenges arise when attempting to execute the node app.js script through the terminal due to various middleware compatibility

I'm a beginner with node.js and I've encountered an issue while trying to run my node app.js file after incorporating a new file named projects.js which contains the following JS code: exports.viewProject = function(req, res){ res.render(" ...

Enhanced jQuery Embed Code validation for user input using a textarea

Currently, I am developing a website that allows users to input embed codes from popular platforms such as Twitter, YouTube, Instagram, Facebook, and so on. The embed code undergoes validation checks and is saved if it meets the criteria. However, when us ...

The route configuration is invalid: it is not possible to use 'redirectTo' and 'canActivate' together

I am looking to implement Laravel Angular JWT authentication, and I am encountering an issue with applying a guard. The error message states: Invalid configuration of route '': redirectTo and canActivate cannot be used together. Redirects happen ...

How to set a timeout for a socket.io connection in a node.js application

After searching through the documentation, I couldn't find a specific solution for expiring or disconnecting a socket.io client after a certain period of time. I am seeking a workaround that is both manageable and asynchronous in node.js. One possibl ...

Ways to identify when a chemical reaction has taken place?

I have developed a Discord bot that interacts with an API related to a game server panel. The bot has tasks to start, restart, stop, and kill the server. I want to enable end users to trigger these tasks by reacting to a specific embed posted by the bot. ...

Creating a Variety of Files in the Angular Compilation Process

Currently, I am developing an Angular project and faced with the task of creating various files during the build process depending on certain conditions or setups. I would appreciate any advice on how to accomplish this within the Angular framework. I att ...

Experiencing a missing handlebars helper error when utilizing a helper within partials in express-handlebars

I have set up custom helpers using express-handlebars like this: const { create } = require("express-handlebars"); // Configuring the handlebars engine const hbs = create({ helpers: require("./config/handlebars-helpers"), }); app.engi ...

When it comes to entering text in a text input or textarea within a large module in Vue.js, taking

While filling out my large form, I noticed a delay in rendering whenever I typed quickly into the input boxes. <b-form-input v-model="paymentItems.tierStepUPYear" type="text"></b-form-input> ...

The item is not functioning properly as intended

After delving into the concepts of prototype and proto, I believed that I had grasped the concept. However, something doesn't seem to add up. Can someone shed light on why directly accessing an Object like this does not yield the desired outcome? fun ...

Error: The dynamic selection function is experiencing an issue where it is unable to read the "map" property of an undefined

Currently, I am in the process of creating a React component that includes the usage of a select HTML input. The implementation is defined as shown below: <select className="form-control-mt-3" id="clientList" name="clientList" onChange={this.handleC ...

Struggling to effectively use XPath to target LI elements that contain specific text

Below is the HTML code for the list item in question: <li class="disabled-result" data-option-array-index="1" style="">4" (0)</li> Here is my attempt at using JavaScript to hide this list item, but it's not working as expected: var xpat ...

The Mystery of Socket.io Random Disconnects (version 1.0.6)

Currently, I am utilizing the most recent version of socket.io (1.0.6) to develop an online multiplayer game using Phaser and Node. One issue that has arisen is that after the clients connect, they will sporadically disconnect without any specific pattern. ...