Unable to retrieve this information using $http callback

I am currently working with angular 1.5 and typescript, but I am facing an issue where I cannot access the 'this' property from the callback returned by the $http promise.

Whenever I try to access a private method from the callback, 'this' is undefined.

Here is the ServerAPI service implementation:

export class ServerAPI implements IServerAPI {
    static $inject:Array<string> = ['$http', '$q'];

    constructor(private $http:ng.IHttpService,
                private $q:ng.IQService) {
    }

    postHandler(partialUrl:string, data?:any, config?:any):ng.IPromise<any> {
        let url = this.buildUrl(partialUrl);

        var result:ng.IPromise< any > = this.$http.post(url, data, config)
            .then((response:any):ng.IPromise<any> => this.handlerResponded(response, data))
            .catch((error:any):ng.IPromise<any> => this.handlerError(error, data));

        return result;
    }

    private handlerResponded(response:any, params:any):any {
        response.data.requestParams = params;
        return response.data;
    }

    private handlerError(error:any, params:any):any {
        error.requestParams = params;
        return error;
    }
}

This service is being used by user.service:

export class UserService implements IUserService {
    static $inject:Array<string> = ['$q', 'serverAPI'];

    constructor(private $q:ng.IQService,
                private serverAPI:blocks.serverAPI.ServerAPI) {
        var vm = this;
        $rootScope.globals = $rootScope.globals || {};
        $rootScope.globals.currentUser = JSON.parse($window.localStorage.getItem('currentUser')) || null;

        this.getUserPermissions();
    }

    private getUserPermissions:() => IPromise<any> = () => {
        var promise = this.serverAPI.postHandler('MetaDataService/GetUserPermissions',
            {userID: this.getUser().profile.UserID})
            .then((res) => {
                this.updateUser('permissions', res.GetUserPermissionsResult); // NOT WORKING, this is undefined
            })
            .catch((response:any):ng.IPromise<any> => {
                this.updateUser('permissions', res.GetUserPermissionsResult); // NOT WORKING, this is undefined
            });
        return promise;
    };

    private updateUser:(property:string, value:any) => void = (property, value) => {
    };
}

Answer №1

The main issue lies within this particular line of code:

.then((response:any):ng.IPromise<any> => this.handlerResponded(response, data))

Even though the lexical scope is maintained to locate the handlerResponded method, it is not completely preserved in the final output.

To address this issue, there are two possible solutions:

  • Include your handler function inline instead of defining it as a method within your class
  • Use the bind method to associate the call to handlerResponded with the instance

An example demonstrating binding:

.then((response:any):ng.IPromise<any> => this.handlerResponded(response, data).bind(this))

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

Passing an event from onSubmit in React without using lambdas

Within our current project, the tslint rule jsx-no-lambda is in place. When attempting to capture event from onSubmit, this is how I typically write my code: public handleLogin = (event: React.FormEvent<HTMLFormElement>) => { event.preventDe ...

Verify that the Angular service has been properly initialized

I am currently testing my Angular service using Karma-Jasmine and I need to verify that the loadApp function is called after the service has been initialized. What would be the most effective approach for testing this? import { Injectable, NgZone } from ...

Adding a new line in the configurations of MatDialogConfig (Angular)

Here is a code snippet: private mDialog: MatDialog, const dialog = new MatDialogConfig(); msg = "I enjoy coding in Angular.\r\n I am learning TypeScript." dialog.data = { message:msg }; alert (msg); mDialog.open(AB ...

Tips on typing the onFocus function event parameter for a Material UI Input component

Currently, I am working on a custom dropdown using material ui components like Input and Popper. The goal is to have the popper open when the user focuses on the input field. Additionally, I am implementing this solution with TypeScript. import ClickAwayL ...

JavaScript - Cannot access the 'name' property on an empty object

I am currently following a React tutorial that demonstrates how to create a useForm hook for linking form input to state. Here is the implementation of the hook: const useForm = (initial = {}) => { const [inputs, setInputs] = useState(initial) ...

What sets apart the definition of isolated scope variables for an Angular directive when done within {} as opposed to in

When working with Angular directives, I am aware that I can assign an isolated scope by adding '=' or '@' or '&' in the {} to define variables. However, it seems like this is not required within the link function. For example: ...

Navigating and Organizing in Ionic Service Factory

Apologies for the beginner question. I am looking to incorporate filtering and sorting by name on my webpage. However, I have encountered two issues after attempting to implement this functionality using a factory in services.js: When typing a search ter ...

Navigate to a different route in AntD Table by clicking on it

I am currently implementing React Router in my navigation component. My goal is to enable users to navigate from screen Y to screen X when they click on a table element. In the past, I achieved this by using "this" command but it seems that it does not ...

Before computing the width, Next.js Swiper slide occupies the entire width

Check out the code snippet below: 'use client'; import { Swiper, SwiperSlide } from 'swiper/react'; import 'swiper/css'; import 'swiper/css/pagination'; export default function Component() { const cards = [{ id: 0 ...

When transitioning to a different page, Angular is creating a duplicate of $scope

My webpage features a section where I showcase all the individuals stored in the database, referred to as the All Persons Page. Within this page, there are two primary options: Add New Person Delete Person (Any selected individual) An issue arises when ...

Using arrow functions in Typescript e6 allows for the utilization of Array.groupBy

I'm attempting to transform a method into a generic method for use with arrow functions in JavaScript, but I'm struggling to determine the correct way to do so. groupBy: <Map>(predicate: (item: T) => Map[]) => Map[]; Array.prototype ...

Error: Couldn't locate Next.js - TypeScript module

I encountered an error with the image, but I am unsure of the reason behind it. Additionally, the directory is included in the second image. import Link from 'next/link'; import { useState } from 'react'; import { ProductModel } from ...

Using ngFor results in duplicate instances of ng-template

I'm facing a challenge with the ngFor directive and I'm struggling to find a solution: <ng-container *ngIf="user.images.length > 0"> <div *ngFor="let image of images"> <img *ngIf="i ...

Encountering a Problem with vue-check-view Library in Typescript

After successfully declaring the js plugin with *.d.ts, I encountered an issue where my view was blank after using .use(checkView). Does the library vue-check-view support Typescript? Error: Uncaught TypeError: Cannot read property '$isServer' o ...

Is it possible for numerous directives to utilize an isolated scope on a single element?

Is it possible for two directives on the same element to share an isolated scope that is separate from their parent? Can they both access properties bound to this isolated scope? For instance, if there are two directives on an element <e-directive a-d ...

Utilize tree-shaking functionality within your TypeScript project

In the process of developing a TypeScript telemetry library using OpenTelemetry, I am exploring ways to incorporate tree-shaking to allow consumers to selectively import only the necessary modules and minimize the overall bundle size. The project directory ...

AngularJS encountered an unexpected JSON token at position 0, causing a SyntaxError

Trying to implement pagination using angularJS and codeigniter. I have a controller named "Cursos" with a function called "api" to fetch the data. The code for the "api" function is as follows: $currentPage = $this->uri->segment(3); # Current page ...

The radio buttons that can be deselected are not accurately retaining their previous value

I'm currently working on a directive that will allow me to deselect an existing radio input. However, I've run into an issue where the directive is not accurately tracking the previously selected value. The objective is to have the radio set to e ...

What is the process for removing globally declared types in TypeScript definitions?

There are numerous libraries that cater to various platforms such as the web, Node servers, and mobile apps like React Native. This means they can be integrated using <script /> tags, require() calls, or the modern import keyword, particularly with t ...

Getting the value or index of an inputbox in AngularJS

Angularjs <tr ng-repeat="advLi in media"> <td> <input style="display:none;" type="text" style="width:35px;" class="form-control" name="mediaindex" value="{{$index+1}}" ng-model="advLi.media_order"> </td> <td& ...