The issue of undefined 'this' in Typescript AngularJS

I have developed a TypeScript service that looks something like this:

export default class MyService {

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

    method1(data : any) : void {
        this.$http(...)
    }

    method2(data : any) : void {
        this.$http(...)
    }
}

Now, I also have a controller class that makes use of this service:

export default class MyController {

    constructor(private myService: MyService, ...) {}

    $onInit(){

        let selectedMethod = true ? this.myService.method1 : this.myService.method2;
        selectedMethod({ ... data ... });
    }
}

The problem arises when the service methods throw an Exception - this is undefined. If I call the methods directly like

this.myService.method1({ ... data ... })
, it works fine. I could, of course, use
selectedMethod.bind(myService)({ ... data ... })
or
selectedMethod.call(myService, { ... data ... })
, but why is there a scope difference in the first place?

Thank you.

Answer №1

When you invoke your method1 method without a context, the value of this inside it will be undefined. To resolve this issue, you can either call the method with the aService object as the context, explicitly set the context using call or apply, or bind the context explicitly using bind:

this.aService.method1(); // In this case, `this` will refer to aService inside the method

method.call(aService, args);

method.apply(aService, [args]);

// Alternatively, you can use `bind`:

let method = true ? this.aService.method1.bind(this.aService) : this.aService.method2.bind(this.aService);

method(); 

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

Which Do You Prefer: Mocha Chai, JEST, or Both?

Apologies if this question is a bit off topic, but I wanted to ask it anyhow. As a beginner, I've been contemplating test-driven development lately. Is it possible to use Jest for testing node/express applications? Or is it necessary to utilize Moch ...

Troubleshooting why content set to a <div> element with JavaScript / jQuery is not persisting after a

This is the current code snippet I am working with: <asp:Button ID="btnSave" runat="server" OnClick="Save" CssClass="StylizedButton" resourcekey="btnSave" /> <div id="lbltot"></div> Below is the JavaScript portion of the code: $(do ...

Utilize Python to extract information from a JavaScript variable that has been parsed with JSON

Recently delving into the world of Python, I am attempting to utilize web scraping to extract data from a website table. However, it appears that the table data is stored within a Javascript variable that has been parsed using JSON.parse. This parsing meth ...

Bug detected in the brfs plugin for browserify

I'm currently working on a project where I need to consolidate all the .html template files into a single bundle.js file by reading the content from each .html file. In my main.js, I have written the following code: var fs = require('fs'); ...

The @Input decorator in Angular 2/4 is designed to only transfer fundamental values and not collections or complex data

I have encountered an issue while attempting to use @Input with a list of objects, where the @Input variable ends up being undefined. What is functioning properly can be seen in home.component.html: <p> <it-easy [mycount]="countItem" (result ...

Is there a way to invoke C# code within a Protractor test?

Is it feasible to leverage C# in executing certain aspects of my Protractor unit tests? The rationale behind this is rooted in the need to extract data from a database and juxtapose it against anticipated outcomes residing in text files. Given the complex ...

Troubleshooting issues with NodeJS server and client connectivity on Cpanel

I've successfully created a nodejs application that functions as a websocket server and serves a basic client webpage. The websocket is running on port 8080, and the client connects through wss://192.168.3.101:8080 when tested locally. However, when I ...

Why does running the code result in the error mentioned above?

Uncaught ReferenceError: Unable to process binding "value: function (){return sumValBinding }" Message: sumValBinding is not defined Here is the HTML code snippet: <div class="form-group"> <label for="inputdefault">First numbe ...

Is there a way to streamline routing in AngularJS similar to how .NET Data Annotation automates tasks?

Understanding the routing system in AngularJS is key, as shown below: .when('/96', { templateUrl: "96.html", animation: 'present' }) .when('/96/moharram', { template ...

Each slider only displays a single database entry

I have an array that retrieves testimonials from a database table and displays them using a foreach loop. I am looking to implement a slider that can fade in and fade out the results. Here is my database query: $showTestimonials = array(); $getTestimoni ...

Occasionally the CUSTOM_ELEMENTS_SCHEMA error may appear intermittently

After updating from Angular 8 to Angular 9, I encountered an error when running the application: error NG8002: Can't bind to 'text' since it isn't a known property of 'app-custom-message'. 1. If 'app-custom-message&a ...

Table depicting the conversion of a JSON array into a string

Currently working on an HTML table with AngularJS integration. My goal is to output the array as a regular string instead of an array format and also ensure the date displays correctly. [{"userId":12,"username":"Smith, Al","date":"2018-03-07T01:00:07.89 ...

Customize dropdown item colors in React using a color picker

I am currently utilizing a react color picker to create a personalized 16 color gradient. The process involves selecting a color from a dropdown menu and then using the color picker to make adjustments. This action updates an array that dictates the stylin ...

Why does "screen.height" function properly when utilizing Chrome's DevTool to emulate mobile devices, yet not on actual mobile devices?

The value of screen.height discussed here can be found at https://www.w3schools.com/jsref/prop_screen_height.asp To determine if the screen height is less than a certain threshold (in this case 560), I utilized screen.height < 560 ? true : false to hid ...

Executing NodeJS awaits in the incorrect order - When using Express with SQLite3's db.all and db.run, one await is prioritized over the other

Need help running asynchronous functions in .exports, getting promises, and using the results in subsequent async functions. Despite using awaits, the second function seems to execute before the first one. sales.js = const sqlite3 = require('sqlite ...

responding with a value of undefined for the get request

My current project involves URL shortening, but I keep encountering an 'undefined' result in my GET request. Additionally, sometimes I also receive a blank page as a result. Despite everything appearing to be correct based on my knowledge, I&apos ...

Unable to run a query in PHP that executes successfully in phpMyAdmin

I'm currently attempting to remove rows from a table using the following code: $query = "Delete from usertour where tourID = $idnum and name LIKE '%$session%' "; However, even when the idnum and session are correct, the row is not being ...

Warning: The use of jQuery load to trigger a Synchronous XMLHttpRequest on the main thread is now considered deprecated

$('#in-view-contents').load("/browse/".concat(selectedId), function(responseData){ var contentsLabelEl = document.getElementById("refined-contents-container"); contentsLabelEl.style.display = "block"; var arrayOfReloadScripts = ["/js/ ...

Using the .map method to filter through JSON data

I'm facing some challenges filtering a .json file to exclude private videos on an app related to a YouTube channel. There are certain videos marked as private that I do not want to display within the app. Can someone assist me in properly filtering th ...

Angular's UI Modal: utilizing inline template and controller functionality

I am looking to create a simple confirmation box using UI-modal, which I have used successfully for more complex modals in the past that load their template and controller from external files. However, this time I want something even simpler - just a basi ...