Encountering a TypeError with Angular 5 Interceptor: The do function is not recognized when using next.handle(...)

While developing an angular interceptor to verify the validity of my auth tokens, I encountered an issue where the do method is not recognized by angular. The alternative solution involving subscribe was effective, but it led to duplicate requests being sent to the server.

TypeError: next.handle(...).do is not a function
at AuthTokenService.webpackJsonp.../../../../../src/app/commons/services/interceptors/auth-token.service.ts.AuthTokenService.intercept (auth-token.service.ts:37)
at HttpInterceptorHandler.webpackJsonp.../../../common/esm5/http.js.HttpInterceptorHandler.handle (http.js:1796)
at XsrfService.webpackJsonp.../../../../../src/app/commons/services/interceptors/xsrf.service.ts.XsrfService.intercept (xsrf.service.ts:15)
at HttpInterceptorHandler.webpackJsonp.../../../common/esm5/http.js.HttpInterceptorHandler.handle (http.js:1796)
at HttpXsrfInterceptor.webpackJsonp.../../../common/esm5/http.js.HttpXsrfInterceptor.intercept (http.js:2489)
at HttpInterceptorHandler.webpackJsonp.../../../common/esm5/http.js.HttpInterceptorHandler.handle (http.js:1796)
at MergeMapSubscriber.project (http.js:1466)
at MergeMapSubscriber.webpackJsonp.../../../../rxjs/_esm5/operators/mergeMap.js.MergeMapSubscriber._tryNext (mergeMap.js:128)
at MergeMapSubscriber.webpackJsonp.../../../../rxjs/_esm5/operators/mergeMap.js.MergeMapSubscriber._next (mergeMap.js:118)
at MergeMapSubscriber.webpackJsonp.../../../../rxjs/_esm5/Subscriber.js.Subscriber.next (Subscriber.js:92)

Take a look at my interceptor code below:

import { Injectable, NgModule} from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from 
'@angular/common/http';
import { SessionService } from 'app/commons/services/auth/session.service';
import { HttpErrorResponse } from "@angular/common/http";
import { StateService } from '@uirouter/angular';

import 'rxjs/add/operator/do';

import * as _ from "lodash";

@Injectable()
export class AuthTokenService implements HttpInterceptor {
  constructor(
    private sessionService: SessionService,
    private stateService: StateService
  ) {}

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

    const currUser = this.sessionService.getCurrentUser();
    const authToken = _.get(currUser, ['auth_token'], null);

    let dupReq = req.clone({ headers: req.headers.set('Authorization', '') });

    if (!_.isNil(authToken)) {
      dupReq = req.clone({ headers: req.headers.set('Authorization', `Token ${authToken}`) });
    }

    return next.handle(dupReq)
      .do(ev => {
        console.log(event);
      })
  }
};

Although I have followed all the necessary steps, the do side-effect mentioned in the guide does not seem to be working as expected.

Answer №1

Realized my error in Angular 5 with the switch to lettable operators. Still wrapping my head around their functionality since I'm a beginner with this technology. After hours of frustration trying to understand interceptors by referring to Angular 4 resources, I stumbled upon a helpful article: Angular 5: Upgrading & Summary of New Features

Here is my updated code:

import { map, filter, tap } from 'rxjs/operators';

@Injectable()
export class AuthTokenService implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        const started = Date.now();
        return next.handle(dupReq).pipe(
        tap(event => {
          if (event instanceof HttpResponse) {
            
console.log(`Request for ${req.urlWithParams} took ${elapsed} ms.`);
          }
        }, error => {
          console.error('NICE ERROR', error)
        })
      )
    }
}

This code flawlessly handles errors from my http requests.

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

Flashing Screens with Ionic 2

I am currently dealing with a situation where my login page and homepage are involved. I have implemented native storage to set an item that helps in checking if the user is already logged in (either through Facebook or Google authentication). The logic fo ...

Select multiple rows by checking the checkboxes and select a single row by clicking on it in the MUI DataGrid

I am currently utilizing the MUI DataGrid version 4 component. The desired functionalities are as follows: Allow multiple selections from the checkbox in the Data Grid (if the user selects multiple rows using the checkbox). Prevent multiple selections fr ...

Testing the creation of elements dynamically with jestLooking into jest for dynamically adding

Attempting to test a dynamic element using TypeScript, but struggling to understand the process. Can anyone offer guidance? Below is the TypeScript file: export default class MyClass { constructor(){ this.render(); } render() { ...

React's memo and/or useCallback functions are not functioning as anticipated

Within my Home Component, there is a state called records, which I utilize to execute a records.map() and display individual RecordItem components within a table. function Home() { const [records, setRecords] = useState<Array<RecordType>>(l ...

What steps can I take to troubleshoot and repair my accordion feature within an Angular project?

As a newcomer to Angular, I recently attempted to create an accordion component but encountered unexpected behavior. Here is the HTML code for my attempt: <div class="faq-item-container"> <h1 class="mt-1 mb-5"><strong>Frequently A ...

What could be causing the errors in my subscription function?

Working on an e-commerce website, I encountered errors in the "cartservice" specifically in the "checkoutFromCart()" function. The console displayed the following error: src/app/services/cart.service.ts:218:81 218 this.http.post(${this.serverUrl}ord ...

Leverage TypeScript to restrict the payload type based on the action name

Utilizing React's useReducer with TypeScript, I am facing an issue where I need to ensure that when the action type is 'SET', the payload has to be an array, and when the action type is 'ADD', the payload should be an object. Here ...

Attempting to utilize Array Methods with an Array Union Type

Currently, I am in the process of refactoring an Angular application to enable strict typing. One issue I have encountered is using array methods with an array union type in our LookupService. When attempting to call const lookup = lookupConfig.find(l =&g ...

Removing/modifying selected choices in an element

I have implemented a material ui select element with the ability to make multiple selections using checkboxes. My query is, can I incorporate the functionality to delete or update names directly from the select element itself? For instance, by clicking on ...

Unable to retrieve template generated using the innerHTML directive in Angular 4

I am in need of accessing the elements of a dynamically created component's DOM through the innerHTML directive in Angular. Below is my main component: import {Component} from '@angular/core'; @Component({ selector: 'app-root', ...

Guide for implementing props in a text area component using React and TypeScript

My react component has a sleek design: import { TextareaHTMLAttributes} from 'react' import styled from 'styled-components' const TextAreaElement = styled.textarea` border-radius: 40px; border: none; background: white; ` const T ...

Frequent occurrence when a variable is utilized prior to being assigned

I am currently working with a module import pino, { Logger } from 'pino'; let logger: Logger; if (process.env.NODE_ENV === 'production') { const dest = pino.extreme(); logger = pino(dest); } if (process.env.NODE_ENV === &apo ...

How to pass a single property as a prop in TypeScript when working with React

I have a main component with a parent-child relationship and I am looking for a way to pass only the product name property as props to my "Title" component. This way, I can avoid having to iterate through the information in my child component. To better i ...

Detecting the language of a browser

In my Angular2 application, I am looking to identify the browser language and use that information to send a request to the backend REST API with localization settings and variable IDs that require translation. Once the request is processed, I will receive ...

Tips for displaying a hyperlink in an Angular 6 component template

In my Angular 6 application, I am facing an issue with a component that is used to display messages on the page. Some of the messages include hyperlinks in HTML markup, but they are not being rendered properly when displayed (they appear as plain text with ...

The TypeScript error message states that the element type 'Modal.Header' specified in the JSX does not contain any construct or call signatures

Currently, I am delving into TypeScript and React development. In my project, I have been utilizing rsuite for its graphical components with great success. However, I recently encountered an issue while attempting to implement a modal dialog using the Moda ...

Errors abound in Angular's implementation of custom reactive form validators

When validating a form for a call center, the fields are usually required to be filled in a specific order. If a user tries to skip ahead, I want to raise an error for multiple fields. I have discovered a method that seems to work as shown below: export ...

The bundling of Angular 2 and RxJS is not happening in Typescript

This is my tsconfig.json { "compilerOptions": { "target": "es5", "module": "system", "moduleResolution": "node", "sourceMap": true, "removeComments": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "n ...

Error: The function createImageUrlBuilder from next_sanity__WEBPACK_IMPORTED_MODULE_0__ is not defined as a valid function

Having some trouble with my Next.js TypeScript project when integrating it with sanity.io. I keep getting an error saying that createImageUrlBuilder is not a function. See screenshot here Here is the code from my sanity module ...

Ways to access the parent value within a child component in Angular 4

I am a beginner in angular4 Currently, I am working on a Registration process that involves multiple steps. To control the visibility of these steps based on certain conditions, I am using the hide/show functionality. The Registration process consists of ...