Exception occurs when arrow function is replaced with an anonymous function

Currently, I am experimenting with the Angular Heroes Tutorial using Typescript. The code snippet below is functioning correctly while testing out the services:

getHeroes() { 
    this.heroService.getHeroes().then(heroes => this.heroes = heroes); 
}

However, when I make a slight modification to the code as shown below, it stops working:

getHeroes(){
    this.heroService.getHeroes().then(function (heroes:Hero[]) {
      this.heroes = heroes;
    })
}

An error message is thrown stating:

Unhandled Promise rejection: This is null ; Zone: angular ; Task: Promise.then ; Value: TypeError: This is null
this.heroes = heroes;

To provide context, I have declared 'heroes' within the class like so:

heroes: Hero[];

Answer №1

The reason for this issue is due to the loss of scope for this when using a regular function instead of an arrow function.

To address this, you can utilize the Function.prototype.bind method:

getHeroes(){
    this.heroService.getHeroes().then(function (heroes:Hero[]) {
      this.heroes = heroes;
    }.bind(this));
}

This approach is suitable if you prefer not to employ the fat arrow function.

Answer №2

Compared to regular function expressions, arrow function expressions have a more concise syntax and lexically bind the this value, meaning they do not bind their own this, arguments, super, or new.target. Arrow functions are always anonymous and are best suited for non-method functions.

In the function below, the this keyword is bound to the callback function's this:

getHeroes(){
    this.heroService.getHeroes().then(function (heroes:Hero[]) {
      this.heroes = heroes;
    })
}

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

Solving Typing Problems in React TypeScript with "mui-icons" Props

I have a small compost project with only an App.JSX file that is functioning perfectly, but now I need to convert it to App.TSX. After changing the extension to .TSX, I encountered two errors that I'm unsure how to resolve. function MyComponentWithI ...

Continuously iterate through collection as it expands over time

As I cycle through an array, I'm performing additional actions that could potentially prolong the loop if new elements are added to the array during iteration. (I understand it's not recommended to modify the object being iterated over, but pleas ...

Trouble accessing data property within a method in Vue 3 with Typescript

I am facing an issue with accessing my data in a method I have written. I am getting a Typescript error TS2339 which states that the property does not exist in the type. TS2339: Property 'players' does not exist on type '{ onAddPlayers(): vo ...

Cache for JSON Schema in VS Code

After updating to TypeScript 1.5 (now out of beta), I am eager to utilize the json schema helpers in VS Code. Upon configuring tsconfig.json, I noticed that only commonjs and amd module options are available, while umd and system are missing based on this ...

"Error: The functionality of finding places on Google Maps is not

I've encountered an issue while trying to integrate Google Maps into my Node application. The map is loading correctly and I'm able to retrieve my location. However, I am facing a problem with implementing the Google Places API code to allow user ...

Alter the class generated by ng-repeat with a click

I currently have a dynamically generated menu displayed on my website, and I am looking to apply a specific class to the active menu item based on the URL (using ngRoutes). The menu items are generated from a $scope.menu object, so my initial thought was t ...

Monaco Editor in TypeScript failing to offer autocomplete suggestions

When using a union type as a parameter of a function in Monaco Editor, the suggestions do not appear. However, in VS Code, the suggestions are provided. Is there a setting I need to enable in Monaco to have the same functionality? Although Monaco provides ...

A guide on how to identify the return type of a callback function in TypeScript

Looking at this function I've created function computedLastOf<T>(cb: () => T[]) : Readonly<Ref<T | undefined>> { return computed(() => { const collection = cb(); return collection[collection.length - 1]; }); } Thi ...

Utilizing the power of AngularJS directives along with the functionality of a

I am completely new to angular js, but I have successfully integrated a jQuery UI datepicker into my Angular JS project. Now, I am facing the challenge of formatting the date selected by the jQuery datepicker into ISO date format. Here is the code snippet: ...

Having trouble with the "Corrupted @import" error during grunt build?

As I embark on my journey to create my very first Angular application, I have encountered a roadblock. Using Yeoman and angular-generator, everything seemed to be running smoothly with "grunt serve." However, when I attempted to execute "grunt build," the ...

Performing a series of HTTP requests within a single @ngrx/effect

I need some guidance as I am new to @ngrx and feeling a bit lost in understanding how it should be used. Let's assume we have an effect named PlaceOrderEffect In this effect, my goal is to handle each request in a specific order. processOrder$ = cre ...

Setting the default value for ngModel does not receive any information from the model

I am trying to populate a form with default values using the code below: <h3>ِStart Time</h3> <div class="row" > <div class="col"> <label for="startTime">Hour(s) </label> <input type="numb ...

Lazy loading in Angular 2 hits a snag when using a module that is shared

After successfully lazy loading my AccountModule, I encountered an issue when adding my SharedModule to it. All of my eagerly loaded modules seemed to be forgotten and I started receiving the following error: The component FoodComponent is not part of a ...

After installing TypeScript community stubs, WebStorm is unable to locate the module

Recently, I tried to incorporate the ramda library into my project and went ahead to install its TypeScript community stubs in WebStorm. https://i.stack.imgur.com/fCFG8.png Despite my efforts, I encountered an error that stated — Cannot find module &a ...

Load Angular scripts only when needed

I need to develop an application that can dynamically register new Angular Controllers obtained from a script. This application should load the minimum necessary scripts at startup and then fetch additional scripts as needed from other modules. Here' ...

Encountering an error in Jest with TypeScript (Backend - Node/Express) that reads "Cannot use import statement outside a module

Currently, I am in the process of developing Jest tests for a Node/Express TypeScript backend. Recently, I came across the concept of global test setup which I am integrating to streamline the usage of variables and function calls that are repeated in all ...

What causes TypeScript to be unable to locate declared constants?

I am facing an issue with the following simple code snippet: const getMethod = 'get'; const postMethod = 'post'; export type RequestMethod = getMethod | postMethod; When I try this code in TypeScript Playground, it shows an error sta ...

Encountering the error "Element implicitly has an 'any' type because expression of type 'string' cannot be used to index type '{}'" can be frustrating when working with React TypeScript

I'm encountering an issue when trying to access an object with an id in the code below. An error message stating 'Element implicitly has an 'any' type because expression of type 'string' can't be used to index type ' ...

Encountering an Uncaught ReferenceError in AngularJS & Jasmine/Karma: require not defined

Recently, I've been delving into the world of testing my angular app with Jasmine-Karma. As someone who is a complete novice when it comes to testing, consoles, and npm, I'd really appreciate a simple explanation (and maybe some guidance) on what ...

Include a new class for angular's user interface tabs

Utilizing Angular UI to build my tabs, I followed the code provided in the documentation: <form name="outerForm" class="tab-form-demo"> <div class="tabbable full-width-tabs"> <uib-tabset active="activeForm"> ...