Angular functions are self-contained and cannot access anything external to their own scope

I created a classic interceptor for Angular, and now I am working on an interceptor for Syncfusion requests. While I have found a solution, I am facing a problem - I am unable to call a method in my function instance. Here is the snippet of my source code:

https://i.sstatic.net/lNXTr.png

import { DataManager, UrlAdaptor } from '@syncfusion/ej2-data';
import { CookieService } from 'ngx-cookie-service';
import { Router } from '@angular/router';
import { AppGlobalService } from '../appglobal.service';

export class CustomAdaptor extends UrlAdaptor {
  router: Router;

  constructor(private AppGlobal: AppGlobalService) {
    super();
  }

  beforeSend(dm: DataManager, request: XMLHttpRequest) {
    request.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
    dm.dataSource.headers = [{ 'Authorization': 'Bearer ' + this.AppGlobal.GetCookie() }];

    request.onloadend = function () {
      if (request.status == 401) {
        this.goBack();
      }
    }
  }

  goBack() {
    this.router = this.AppGlobal.GetRouter();
    this.router.navigate(['login']);
  }
}

My main goal is to redirect to the login page if a 401 error occurs. It would be more efficient if I could directly call the login page without using the goBack method.

Answer №1

Every function declaration creates its own unique context, with the default value of this referring to that context. To maintain the value of the outer this, you can substitute function with arrow function.

request.onloadend = () => {
   if (request.status == 401) {
      this.goBack();
   }
}

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

building an angular feature that displays dynamic checkboxes in rows based on certain conditions

In my Angular application, I am generating dynamic components such as checkboxes, radio buttons, textboxes, etc. based on server configuration. The issue I am facing is with displaying checkboxes in column settings. For example, if there are 6 checkboxes a ...

Turn off integrity verification for local dependencies in package-lock.json

Is there a way to bypass the integrity check for a local dependency in package-lock.json? Within my project repository, I have a core library along with two Angular applications that both rely on this core library as a dependency. The problem arises beca ...

Verify if an array contains a specific string while disregarding any additional letters within that string

Let's say I have a variable: var url = "/login/user"; Along with an array: var x = ["login", "resetpassword", "authenticate"]; My goal is to check if the url string exists within the array. The issue arises because the url contains additional char ...

Efficiently utilizing ngrx by orchestrating various services and actions to achieve accurate mapping

Combining multiple effects into one is my current goal due to an issue with dispatching actions separately. The aim is to execute sequentially after verifying the value returned from the first service call. Here are the three separate effects I have: @Eff ...

Having trouble with errors when adding onClick prop conditionally in React and TypeScript

I need to dynamically add an onClick function to my TypeScript React component conditionally: <div onClick={(!disabled && onClick) ?? undefined}>{children}</div> However, I encounter the following error message: Type 'false | (() ...

The compilation of the Angular application is successful, however, errors are arising stating that the property does not exist with the 'ng build --prod' command

When compiling the Angular app, it is successful but encountered errors in 'ng build --prod' ERROR in src\app\header\header.component.html(31,124): : Property 'searchText' does not exist on type 'HeaderComponent&apo ...

Angular - which variables should be declared inside or outside of the exported class?

Check out this Angular tutorial at: https://stackblitz.com/angular/qmgqmlrqmye?file=src%2Fapp%2Fhero.service.ts One interesting problem in the tutorial is that we need to define httpOptions outside of the HeroService class, while heroesUrl must be defined ...

Issue with Angular @Input when navigating back in browser causing component to not render

Within the parent component, I am fetching a list of products from the store: // ... ngOnInit() { this.products$.subscribe(products => { this.products = products; }) } // ... <!-- ... --> <ng-container *ngIf="products"> ...

Examining the asynchronous function to cause an error using mocha

I am facing a challenge with testing an async function that is supposed to run for 2000ms before throwing an exception. Despite my efforts using Mocha / chai, the test does not seem to be working as expected. Here's what I have attempted: First appr ...

Top tips for creating effective Angular 2 components

My application features a user object that stores and updates all user information using an observable provided by the userService. I am now contemplating the best practice for utilizing this user observable with components. One specific scenario involves ...

Utilizing D3 to fetch geographic data in the form of a TopoJSON file for U.S. counties

After retrieving a set of coordinates, the goal is to use D3 to find the corresponding county from a U.S. TopoJSON file. Here is an example code snippet: navigator.geolocation.getCurrentPosition(function(position) { let coordinates: [number, number] = [p ...

Is there a way to prevent the splash screen from appearing every time I navigate using a navbar link in a single page application (SPA)?

Recently, I came across this tutorial and followed it diligently. Everything seemed to be working perfectly until I encountered an issue with my navbar links. Each time I clicked on a link, the splash screen appeared, refreshing the page without directing ...

Switching ng-loading from a different component

I am currently utilizing ngx-loading and I would like to have the ability to control its visibility from child components. This is my current setup: Main Component import { Component, Injectable } from '@angular/core'; @Injectable() export cla ...

Placing files in the "Dist" folder is causing an issue by disrupting the functionality of the Angular 2 app

For testing my login component in Angular2, I am using a mockBackend within my app. Initially, the standalone version of the login worked perfectly fine. However, when trying to integrate it into my ongoing development project, I encountered an issue. Duri ...

The server will only respond with a 200 status code to an OPTIONS request

My current situation bears some resemblance to this inquiry, although there are some differences and no solutions provided. In my case, the backend is in Python and the front-end is Angular. The live server runs on Ngnix/Unix while development is on Windo ...

Retrieve all the items listed in the markdown file under specific headings

Below is an example of a markdown file: # Test ## First List * Hello World * Lorem Ipsum * Foo ## Second List - Item 1 ## Third List + Item A Part of Item A + Item B ## Not a List Blah blah blah ## Empty ## Another List Blah blah blah * ITEM # ...

Every time I attempt to destructure the state object in react typescript, I encounter the error message stating 'Object is possibly undefined'

Whenever I attempt to destructure my state object in react typescript, I encounter an error stating Object is possibly 'undefined'. When I try using optional chaining, a different error pops up saying const newUser: NewUser | undefined Argument o ...

Tips on enabling click function in an ionic infowindow

After creating a div in my HTML file and referencing it in my TS file using document.getElementByID, I utilized its inner HTML as the content for an infowindow. However, despite my efforts, I am unable to get clicks working. Adding event listeners to any e ...

Tips for integrating Tesseract with Angular 2 and above

I'm currently exploring the use of Tesseract within one of my components for OCR processing on a file. .ts: import * as Tesseract from 'tesseract.js'; fileToUpload: File = null; handleFileInput(files: FileList) { this.fileToUpload = f ...

What is the correct way to install @angular-devkit/build-angular in Angular version 13?

In my Angular 13 project, I am facing a dilemma with conflicting dev dependencies: "devDependencies": { "@angular-devkit/build-angular": "~13.2.5", "@angular/cli": "~13.2.5", "@angular/co ...