Service error: The function of "method" is not valid

In one of my Angular 2 applications, I have a class that contains numerous methods for managing authentication. One particular method is responsible for handling errors thrown by the angular/http module. For example, if a response returns a status code of 401, this handler method will trigger a logout method within the same class using `this.logout()`. However, when I build and test the app in a browser, I encounter an error stating "this.logout() is not a function" whenever an HTTP request responds with a 401 status code.

public handle(error: Response | any, caught: Observable<any>): Observable<ResponseError> {
    let errRes: ResponseError;

    if (error instanceof Response) {
        const body = error.json();

        errRes = { message: body.message, statusCode: error.status };

        if (body.hasOwnProperty('authCheck')) {
            errRes.authCheck = body.authCheck;
        }

        if (_.inRange(errRes.statusCode, 401, 403)) {
            this.logout()
        }

    } else {
        const errMsg = error.message ? error.message : error.toString()
        errRes = { message: errMsg }
    }

    return Observable.throw(errRes)
}

Answer №1

Please note: I do not have experience with Typescript

In the world of JavaScript (I cannot speak for typescript, but it's safe to assume), the this keyword does not retain the context in your callback functions.

To work around this issue, you can declare something like let _this = this; in your services to preserve the context when the callback is invoked. In this case, _this would represent the context of your logout method.

let _this = this;
_this.logout = function() { ... };

Then, instead of using this.logout();, you can use:

if(_.inRange(errRes.statusCode, 401, 403)) {
    _this.logout()
}

Answer №2

After some troubleshooting, I believe I have discovered the resolution to the issue at hand. It turns out that I was mistakenly passing the method/function into the context of another function (handle). By making the following adjustment:

func((error, caught) => {
    return handle(error, caught)
})

the issue has been resolved and everything is functioning as expected. Your insights were greatly appreciated. Thank you.

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

A guide to replacing or customizing standard components in ReactJS

I need to modify the color property of a common component so I can use it elsewhere. const ViewAllIcon = (props) => ( <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 26 ...

The Vue JS Option element requires the "selected" attribute to be utilized as a property instead

I'm attempting to automatically have an option selected if the "selected" property is present on the option object. Here is my code snippet: <template> <select v-model="model" :placeholder="placeholder"> <option v-for="opt ...

Raspberry Pi Fast Server: Issue with AJAX not locating images in directory and malfunctioning ID search

I'm completely new to Raspberry Pi, linux, and server concepts, so I'd appreciate explanations at a beginner level. My goal is to create a display similar to those you see in lobbies showing corporate slides and weather updates. While setting up ...

The feature for adding a function in Moment.js seems to be malfunctioning

Unfortunately, the moment().add() function is not functioning properly in my JavaScript code. var theDate = moment(event.start.format("YYYY-MM-DD HH:mm")); //start Date of event var checkquarter = theDate.add(30, 'minutes'); var plus = 30; if ...

What causes the issue of Angular 9 routing breaking upon page refresh?

I have deployed my Angular 9 application on Heroku and everything is working perfectly. However, when I refresh the page or copy/paste a link, I get an error message saying "Cannot GET /XXX/XXX". Only the root link seems to work! Initially, I can navigate ...

What is the best way to emphasize the current page within my Bootstrap <nav> menu?

Below is the Bootstrap code that defines our main menu navigation: <div class="col-xl-9 col-lg-9"> <div class="main-menu d-none d-lg-block"> <nav> ...

What are the best methods for ensuring a website maintains consistent visibility across all different screen sizes?

Recently, I created a website tailored for a viewport size of 1366px by 768px. My goal is to maintain the same design regardless of the browser window size without implementing responsive design techniques. For instance: When viewing the website on a 360 ...

Utilizing ASP.NET Core MVC in conjunction with Angular and Identity Server 4 for seamless integration with web API connections

Posting here after receiving a response from this post -------------------------------------- In the midst of developing an application with an MVC core app that loads an angular application. The angular app will connect to a Web API for CRUD operations. ...

The outcome of AES encryption varies when comparing Node JS with C# programming languages

In a particular scenario, I need to encrypt and transmit text using the AES 256 algorithm. The decryption process will be handled by client-side C# code. Here is the encryption code in JavaScript: const crypto = require('crypto'); algorithm = ...

The process of obtaining points through accurate responses using form inputs

My task is to create a unique quiz consisting of 10 questions. Half of the questions are multiple choice, which require radio inputs, while the other half are written answers that need text inputs. To ensure accuracy and provide a scoring system, I came ac ...

After successfully logging in, the deployed server encounters an Error 503 and shuts down. However, on the development environment, everything runs smoothly as

I am currently in the process of developing an application using NET 6 LTS and Angular 14. Everything runs smoothly on my development environment with IIS express. However, once I deploy the application (release version) on Windows 2019 with IIS 10, I enco ...

How Angular 2's change detection system causes unnecessary DOM refreshing

My application is currently in the live beta stage and I am focused on improving its performance. One issue that has caught my attention is the flickering of images within a table. Upon investigation, I discovered that the DOM is continuously refreshing, e ...

Oops! An issue occurred while trying to compile the file constructor.d.ts in the common-behaviors folder of @angular/material/core. The error message received was: "error TS1005: ';'

Switching from Bootstrap to Angular Material caused an unexpected error when trying to run ng serve: Error: node_modules/@angular/material/core/common-behaviors/constructor.d.ts:14:64 - error TS1005: ';' expected. The errors encountered include: ...

Issues with POST data not being received by MVC 4 APIController

Although this issue has been addressed numerous times, I am still unable to pinpoint the error! Here is a straightforward JS script that sends data back to the ApiController. function WebCall(url,parameterObject, callBackFunction) { this.callbackfunction ...

JavaScript HTTP Requests

I came across this AJAX example in Stoyan Stefanov's book Object Oriented JavaScript on page 275. The example involves requesting three different files. I have a few questions that I was hoping someone could help me with! What does the line xhr.se ...

Customize the appearance of a React component depending on its unique identifier

After creating a simple TODO app with drag and drop functionality, I am now looking to apply a line-through CSS style to any task added or dragged into the second column of my app. What is the best way to target these tasks using their unique ID: <div c ...

Choose the list item below

I'm working on a website that includes a select list with images. Here's what I have so far: When I choose an image from the list, it should display below. <?php // Establish database connection $con=mysqli_connect("******","***","*** ...

Steps to extract a hash from a document's URL

The following code is used: jQuery(document).ready(function() { console.log($(this)); }); After running this code, the object displayed in the console is: [Document mypage.html#weather] How can I retrieve the last ID from this object? In this ...

An unusual html element

During a recent exploration of a website's code using the inspect tool, I stumbled upon a tag that was completely unfamiliar to me. <gblockquote></gblockquote> I've come across a blockquote before, but never a gblockquote. Interest ...

Creating a dynamic JSON array with a single key as an array

After converting data from an excel sheet into a json array, here is the structure: [{ 'booktitle': 'Leading', 'bookid': '56353', 'bookauthor': 'Sir Alex Ferguson' }, { 'booktitle&ap ...