Error: Unable to access $rootScope in the http interceptor response function

I have set up an interceptor to display an ajax spinner while loading.

interface IInterceptorScope extends angular.IRootScopeService {
        loading: number;
    }

    export class Interceptor {

        public static Factory($q: angular.IQService, $rootScope : IInterceptorScope) {
            return new Interceptor($q, $rootScope);
        }


        constructor(private $q: angular.IQService, private $rootScope: IInterceptorScope) {
            this.$rootScope.loading = 0;
        }


        public response(response) {
            console.log(response);
            this.$rootScope.loading = 1;
            return response || this.$q.when(response);
        }

        public responseError(rejection) {
            console.log(rejection.status);
            if (rejection.status === 401) {
            }

            return this.$q.reject(rejection);
        }
    }

Encountering the following error:

https://i.sstatic.net/FkcBO.jpg

The issue is that $q is not defined. I am unsure why this is happening. Can someone assist with this?

EDIT: Here is how I'm adding the interceptor in my config() block, the relevant snippet looks like this:

.config($httpProvider : angular.IHttpProvider) => {
     $httpProvider.interceptors.push(Interceptor.Factory);
}

And registering the factory:

.factory('Interceptor', Interceptor)

For reference, I was checking out the first answer mentioned here:

AngularJS global $http state ajax loader

The plain JavaScript implementation uses $rootScope with the loading property, but I'm uncertain if this relates to the TypeScript setup in the code above.

Answer №1

When working with Angular, the response method is called without setting the context of this. To address this in TypeScript, you can utilize a function property to capture this like so:

public response = (response) => {
   console.log(response);
   this.$rootScope.loading = 1;
   return response || this.$q.when(response);
}

The same technique applies for handling the responseError.

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

What is the process for implementing a version folder for my @types/definition?

Is there a way to access the typings for react-router in my project? My package.json file currently has this dependency: { "@types/react-router": "^4.0.3" } However, it seems to be using the standard index.d.ts file from DefinitelyTyped library which i ...

What is the best way to incorporate a formArray into a formGroup?

Before anything else, I want to apologize for any errors in my English. I seem to be having trouble adding an array field to a formGroup. My issue arises when attempting to use the push method to add a formArray to my rate formGroup. It appears that the ...

ng filtering with a controller-defined scope

I am currently working on a webpage with AngularJS and I am looking to implement some filters on the site. Here is the HTML code I have: <div ng-repeat="data in datas | filter:{area:course} | filter:{subject:subFilter} | filter:{city:cityFilter}"> ...

Simulating chained responses in Express using JEST

I am relatively new to using jest and typescript, currently working on creating a unit test for a controller function in jest import { Request, Response } from 'express'; const healthCheck = (_req: Request, _res: Response) => { const value ...

Following the recent update to webpack-dev-server and webpack, certain modules are being requested that do not exist in the project

Recently, I made updates to my project that involved Vue.js and Typescript. After updating webpack and webpack-dev-server, I encountered a problem where certain modules were missing when attempting to run the project in development mode. Here is some addi ...

step-by-step guide for implementing Firebase JavaScript simple login in Cordova

Having an issue with the integration of Angular Firebase JavaScript simple login in Cordova. This problem only occurs when testing on cordova emulate android User clicks on Google login button Redirected to Google login page After submitting the login f ...

Utilizing AngularJS: Triggering a controller function from a directive

I am currently working on a project with a model named 'user', which includes a controller called 'login' and a directive called 'userMenu'. My goal is to have the userMenu directive utilize the 'login' controller th ...

Obtain the object literal string with additional decorative strings surrounding it

In my current Typescript code, I have an object literal structured like this: const MyNamesStrings = { a: { b: "hello", c: "bye" } d: { e: "qwerty" } } However, I am looking for a way to wrap these strings with add ...

Tips for utilizing a shared controller in an Angular Material popup dialogue

Within my project, Angular Material is being used for various dialogs, primarily for alert purposes. However, I now find myself in need of a more complex dialog. The example provided on the Angular Material site showcases how to create a dialog: function ...

Developing a custom camera system for a top-down RPG game using Javascript Canvas

What specific question do I have to ask now? My goal is to implement a "viewport" camera effect that will track the player without moving the background I am integrating websocket support and planning to render additional characters on the map - movement ...

Leverage the power of JSON objects within your Angular.js application

Is it possible to request a JSON object, such as the one in employes.json file: {"employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ]} Then, how can I util ...

How come I am unable to reach a function within an AngularJS service following the "then" promise? (refer to code)

I'm encountering an issue with this error message: TypeError: Object [object global] does not have the method 'setApiToken' angular.module("userService", ["restangular", "angular-cache"]).factory "userService", (Restangular, $angularCacheFa ...

Error not caught: AngularJS module error

Initially, I was hesitant to ask this question, but after struggling for two hours without any success, I've decided to seek some assistance. I'm trying to integrate the ngResource module into my application. Prior to this, everything was functi ...

Express server having issues with AngularJS integration

Currently delving into the world of AngularJS and experimenting with some basic examples. Successfully installed Node and utilized npm to incorporate express in the designated directory for my projects. Following a straightforward example to display an htm ...

Transforming an array of JSON items into a unified object using Angular

I need to convert an array list into a single object with specific values using TypeScript in Angular 8. Here is the array: "arrayList": [{ "name": "Testname1", "value": "abc" }, { "name": "Testname2", "value": "xyz" } ] The desired ...

Developing a full stack web application using AngularJS, Node.js

I am interested in creating a web application that utilizes MySQL, Node.js, and AngularJS for CRUD operations. Can you provide guidance on how to start this project? Despite my efforts to develop the application, I have encountered numerous challenges and ...

The asynchronous module has finished even though there is another operation still pending

Currently, I am working on connecting to the Quickbooks API and downloading employee information to save it in my local database. To achieve this task, I am utilizing AngularJS and WebAPI. However, I have encountered an error when attempting to save the in ...

Is there a way to prevent IntelliJ from creating .js files when working with .ts source code?

Working on a mixed Java/Typescript project with Maven as the build tool, I utilize the frontend-maven-plugin to successfully build from the command line. However, I am encountering an issue with IntelliJ 2018.2 where it keeps transpiling .js files for my . ...

angularjs routing in webpack not functioning as expected

Looking for assistance I'm facing an issue with my app routing. It loads the home page properly, but when I try to navigate to the login page, nothing happens. It seems like it can't locate the login page, even though I have registered it. I&apos ...

How can I show distinct values in the Angular Material dropdown menu?

I am currently working on implementing a feature where I need to show unique options for the select using angular material. Below is what I have so far: where appitem is an array of items. <mat-form-field> <mat-select placeholder="Select app ...