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

The angular 5 application encountered an issue where it was unable to access the property 'singlePost' due to a null value, resulting

When using the once method to fetch data from the Firebase database, everything works correctly. However, when I try to use the on method, I encounter an error that says: ERROR TypeError: Cannot read property 'singlePost' of null. How can I prope ...

Windowing box inside a container box

I am looking to implement scrolling for just the "chat-messages" div within the "chat-bar" div on my site. I want only this specific section to be scrollable, while the rest of the site remains stationary. Currently, I have to scroll through the entire pag ...

Multiple Invocations of Angular Observable Service

I am facing an issue with my service method that returns an observable. In my component, I subscribe to this observable when it is loaded and have added a console.log in the service to track each time it is called. Upon running my application and checking ...

The routing feature functions properly on localhost but encounters issues on the live server

There seems to be an issue with this code. While it works perfectly on localhost, it doesn't function as expected on a live Apache server. I have already specified the homepage in the package JSON file and included an htaccess file. However, when acce ...

Is there a way to dynamically set the value of a React Material TextField in Auto Select mode?

Here is a React state: const [filterByInvoiceNo, setFilterByInvoiceNo] = useState( 0 ); This represents a React Material TextField: <TextField size="small" type="number" label="Invoice No&quo ...

Is it possible to customize the MUI CSS for a specific menu item using the sx prop?

How can I apply the MenuItemStyle to the sx prop of a MenuItem using: const MenuItemStyle = { '&:hover': { backgroundColor: `${theme.color.secondaryHover}`, }, '&:selected, &:selected:hover': { backgroundColor: ...

Incorporate a pair of functions within the (click) directive in Angular 5

I am trying to implement two functions that should execute on click <li class="active" (click)="routeTransaction(); activateClass(classChange)" *ngIf="permissionKeys.indexOf('TRANSACTIONS')>-1" [ngClass]="{'liactive': classChange ...

Having trouble accessing data from the local storage?

const headers = new Headers({ 'access_token' : accToken, 'Content-Type': 'application/json', }); axios.post(baseURI, data, { headers: headers }) ...

Obtaining information from node.js module to the server.js script

I am attempting to extract data from a function within a node module, which returns a JSON object. My goal is to display this JSON object in a router located in my server.js file. This is how I am trying to export it: // Function Export exports.g ...

Do other effects promptly process actions dispatched by one ngrx Effects effect?

I am facing an issue in my Angular (2) application where I have implemented four ngrx actions: START This action is not processed by the reducer, meaning there is no state change The ngrx Effect triggers an asynchronous task and maps it to either SUCCE ...

A more efficient method for tallying values within an object (JavaScript, React)

Is there a more efficient way to determine the count of items with a specific key/value pair in a React state? When the list is large, this method may become a bottleneck. To illustrate the question, consider the following simplified example: class App ...

Effectively Monitoring Angular Router Link Status

Is anyone else facing an issue with router link active not working correctly when navigating to a route with a different ID? The class is applied on the first navigation, but not on subsequent navigations. Any solutions? This is my HTML file: <div clas ...

What is the best way to assign a variable with the type (x:number)=>{y:number,z:number}?

I am trying to initialize a variable called foo, but my current code is not compiling successfully. let foo: (x: number) => {y:number,z: number} = (x) => {x+1, x+2}; This results in the following error: Left side of comma operator is unused and ha ...

Stop images from constantly refreshing upon each change of state - React

Within my component, I have incorporated an image in the following way: <div className="margin-10 flex-row-center"> <span> <img src={spinner} className="spinner" /> ...

Load prior state when the value changes with UseState in NextJS

In the development of my e-commerce application, I am currently working on implementing filters based on category and price for the Shop page. To handle this functionality, I have established the initial state as follows: const [filters, setFilters] = useS ...

Before fetching the data from firebase in Angular 2, it is crucial to ensure that the code is properly

I'm facing an issue when trying to retrieve data from Firebase. It successfully retrieves the data, but it takes a few seconds to do so. In the meantime, the code continues running and the variable's value becomes null. Why is this happening? Is ...

How can a TypeScript function be used to retrieve a string (or JSON object)?

When attempting to retrieve data from a web API using TypeScript and return the JSON object, encountering an error has left me puzzled. Inside my function, I can successfully display the fetched data on the console, but when I try to return it with return ...

Exploring AngularJS: the power of directives and the art of dependency

According to Angular documentation, the recommended way to add a dependency is by following these steps: Source //inject directives and services. var app = angular.module('fileUpload', ['ngFileUpload']); app.controller('MyCtrl&ap ...

Looking for some help with tweaking this script - it's so close to working perfectly! The images are supposed to show up while

Hey everyone, I'm struggling with a script issue! I currently have a gallery of images where the opacity is set to 0 in my CSS. I want these images to become visible when scrolling down (on view). In this script, I have specified that they should app ...

Creating a personalized <select> filter in Angular.js with two different JSON choices

I am working with a Q&A JSON feed that includes the following: "questions": [ { "answer": "Ea et non sunt dolore nulla commodo esse laborum ipsum minim non.", "id": 0, "poster": "Chelsea Vang", "question": "Ex ex elit cu ...