The 'mergeMap' property is not found on the 'Observable<any>' type

Currently, I'm working on an HttpInterceptor within my Ionic 4 application. My goal is to retrieve the Bearer Authorization token stored in local storage.

Although I attempted to utilize mergeMap for this task, I kept encountering the following error:

Property 'mergeMap' does not exist on type 'Observable<any>'

Below is the complete code snippet extracted from the file token.interceptor.ts:

import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError, from  } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { Router } from '@angular/router';
import { Storage } from '@ionic/storage';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

    token: any;

    constructor(private router: Router, private storage: Storage) {}

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

        return from(this.storage.get('User')).mergeMap((val) => {
            if (this.token) {
                request = request.clone({
                    setHeaders: {
                        'Authorization': this.token
                    }
                });
            }

            if (!request.headers.has('Content-Type')) {
                request = request.clone({
                    setHeaders: {
                        'content-type': 'application/json'
                    }
                });
            }

            request = request.clone({
                headers: request.headers.set('Accept', 'application/json')
            });

            return next.handle(request).pipe(
                map((event: HttpEvent < any >) => {
                    if (event instanceof HttpResponse) {
                        console.log('event--->>>', event);
                    }
                    return event;
                }),
                catchError((error: HttpErrorResponse) => {
                    if (error.status === 401) {
                        if (error.error.success === false) {
                            // this.presentToast('Login failed');
                        } else {
                            this.router.navigate(['/']);
                        }
                    }
                    return throwError(error);
                }));
        })

    }

}

In an attempt to resolve the issue mentioned in this thread, I experimented with the suggested format:

return from(...).pipe(mergeMap(...));

Unfortunately, this approach did not yield the desired outcome.

Could anyone provide alternative suggestions or solutions that I could explore?

Answer №1

Your code is currently using the outdated syntax for RxJS:

import 'rxjs/operators/mergeMap';
myObs$.mergeMap(anotherObs$);

With the updated RxJS API (version 5.5+), the mergeMap method has been replaced with a function that is used within the pipe operator, like so:

import { mergeMap } from 'rxjs/operators';
myObs$.pipe(mergeMap(anotherObs$));

Answer №2

Make sure to update your imports

import { map, catchError, mergeMap } from 'rxjs/operators';

You can now implement mergeMap in a pipe.

const { of } = rxjs; // Using object destructuring instead of import for snippets
const { mergeMap } = rxjs.operators;

of(4).pipe(
  mergeMap(val => of(val * 2))
).subscribe(result => {
  console.log(result);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.4.0/rxjs.umd.min.js"></script>

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

Exploring the functionality of promises in JavaScript

Currently, I am using the most recent version of Angular. The code snippet I've written looks like this: $q.all({ a: $q.then(func1, failHandler), b: $q.then(func2, failHandler), c: $q.then(func3, failHandler), }).then(func4); Is it guaranteed ...

Ways to identify the moment a form becomes 'ready' after the component has been initialized

It seems like I might be making a mistake, as there are instances where I need to make adjustments to a Form or FormControl after a component has initialized and data has been loaded. The problem arises because the form and its controls don't seem to ...

What is the best way to handle multiple requests to the same URL in Cypress while waiting?

I am currently developing a Cypress test that involves sending multiple requests to the same URL with varying body content. Essentially, the test modifies input values in the user interface, triggering new server requests. The challenge arises when trying ...

Having issues delivering static JavaScript files to the client's browser using express.js

I'm looking to create a simple blog application using express.js, where I can write and store posts in a database directly from the browser. After some research, I found the ckeditor package, which allows for formatting before submission. I attempted ...

Tips for eliminating empty trailing values and Carriage Returns from a JavaScript array

I needed a way to eliminate empty elements and Carriage Returns from the end of an array. Here's an example of what my array looks like: Input arr: ['', 'Apple', '', 'Banana', '', 'Guava', & ...

Animating three-dimensional objects using Three.js in real-time

I have been working with three.js and have successfully animated some objects using the animate() function. Here's a snippet of my code: function animate(){ object.position.z++; } The issue I'm facing is that this function is called every r ...

arrow function implemented in a React hook for handling onClick event

From my understanding, placing an arrow function in the JSX creates a new reference of a new function each time it is triggered. For example: <p onClick={() => handleClick() /> In older versions of React with classes, we could do this: <p onCl ...

Create a regulation that permits access solely to individuals currently logged into the system database

I am a beginner when it comes to working with Firebase and its rules. My goal is to implement a system where each user in the Firestore database has a boolean field called isOnline, as shown in the image I have attached. https://i.stack.imgur.com/7M3dc.pn ...

Bringing elements into perfect harmony in Angular

Seeking guidance on HTML alignment using bootstrap for prebuilt components like buttons. Struggling with aligning divs and looking to learn more about grouping them together for proper alignment. Goal is to center elements on screen one above the other. ...

Change the parent title attribute back to its original state

This is in contrast to queries similar to the one referenced here. In my scenario, there is a child element within a parent element (specifically a matSelect within a matCard, although that detail may not be significant) where the parent element has a set ...

Elevated UI Kit including a setFloating function paired with a specialized component that can accept

I am currently experimenting with using Floating UI alongside various custom React components. These custom components create internal element references for tasks like focus and measurements, but they also have the capability to accept and utilize a RefOb ...

Issues have arisen with Google Maps functionality following the API integration, resulting in a blank grey

I am experiencing an issue with Google Maps where it is displaying a grey box or sometimes showing nothing/white. I have tried various solutions found online but none of them have worked for me. Does anyone have a solution? I even attempted to change the ...

Navigate a first person simulation using three.js and control your movements with the keyboard arrow

To access my reference material, please go to http://jsfiddle.net/fYtwf/ Overview I am working on a basic 3D simulation using three.js where the camera is surrounded by cubes in three dimensions. These cubes serve as a visual guide to where the camera is ...

Strategies to manage or prevent a timezone offset while deploying a Next.js application on Vercel

Is there a way to ensure that a React/Next.js App always displays the local time in CEST, regardless of the user's location? For example, if I receive GMT time from the backend and want to offset it to display the CEST timezone, how can I achieve this ...

Transmitting a JSON string to my backend system to insert into my database, but unfortunately, no data is being added

I've been facing a challenging issue with my code Currently, I am attempting to insert an object into my database using jQuery/AJAX. Despite not encountering any errors, the data is not getting added to my DB. Here is the snippet of my JS/JQuery cod ...

Is there a way to manage the state of a dictionary nested within a list using React JS?

Below is a snippet of my code. I am attempting to update the state of data (which is contained within datasets) to a value defined by the user. constructor(props) { super(props); this.state={ value:'', set:[], coun ...

Why does the selectedItems in the AngularJS grid keep coming back as undefined?

Is there a specific reason why the angularjs grid in my sample isn't displaying the selectedItems properly? Every time I attempt to reference the selectedItems, it returns "undefined." I have tested this in both Chrome and IE with identical outcomes. ...

Is there a way to completely remove an element from the dom once the ajax call has returned

I've been struggling to completely remove LI elements and their content, including the checkbox input, from the DOM without success. After an ajax callback, I am calling the following function, but it only removes the contents and not the element its ...

Error encountered in node.js script due to misuse of Sqlite's SQLITE_MISUSE functionality

Upon running my code with this query, I have encountered a situation where all tables are listed sometimes, while other times only one table is shown and consistently the following error is displayed: Query Error: Error: SQLITE_MISUSE: unknown error I ha ...

Error: An unhandled exception occurred during component destruction: TypeError: Cannot access property 'unsubscribe' of undefined

I encountered an issue while trying to unsubscribe during the ngOnDestroy method in my shopping-edit.component.ts file, specifically when clicking on the link to navigate to my recipes page. Here is a screenshot demonstrating the error: error on link clic ...