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

Moving Angularjs table rows to another tableMoving table row from one Angular

I need a solution for transferring rows from one table to another. Here are the two tables involved: First Table: <table> <tr ng-repeat="row in items"> <td>{{row.PRODUCTDESCRIPTION}}</td> <td><inpu ...

Suggestions for organizing files

I am in search of an optimal file structure for a website that incorporates an Angular front-end and a Php Slim API. My current setup is as follows: index.html = Starting point for Angular api/ index.php = Starting point for Slim .htaccess = redirects ...

A date picker pops up when the user clicks on an Angular input field of type text

I am looking to edit a dateTime value using Angular/Ionic, but unfortunately there is no dateTime picker available. To work around this issue, I have split the field into separate date and time fields. In order to incorporate placeholder text and format th ...

NestJS Logger: Issue setting logger types in main.ts

When attempting to specify logger types in main.ts as illustrated in the official documentation: const app = await NestFactory.create(ApplicationModule, { logger: ['error', 'warn'], }); await app.listen(3000); I am encountering an i ...

What is the best way to designate external dependencies in WebPack that are not imported using '*'?

I need assistance with specifying office-ui-fabric-react as an external dependency in my TypeScript project using Webpack. Currently, I am importing only the modules I require in my project: import { Dialog, DialogType, DialogFooter } from 'office-u ...

The JSON object, which has been converted into a string and sent over the network,

Attempting to set up a websocket server using TypeScript in Node.js, the following code was used: ws.on('message', (msg: string) => { console.log("got message:" + msg); const m = JSON.parse(msg); console.log(m); ...

Sharing information with connections through a REST API

Currently in the process of developing an API where I need to create a Post. The specific structure for this Post is as follows: { "Title": "Blog first post", "Body": "Some body text for the post", "PublishedAt": "2016-02-08", "Category": { "I ...

TypeScript creates a .d.ts file that contains declaration statements rather than export declarations

When compiling my code using the command tsc --p typescript/tsconfig.json --outFile "dist/umd/index.d.ts", I encountered an issue. The contents of my tsconfig.json file are as follows: { "include": ["../src/**/*"], "exclude": ["../**/*.test.ts"], ...

The InjectionToken component is not exported by AngularFire

I am running into some challenges while trying to develop an Angular-Fire application. I was following a specific tutorial which can be found at: However, when I integrate angular-fire into my application, I encounter an issue where the "server" fails to ...

Monitoring data updates within an Angular directive

Is there a way to activate a $watch variable in an Angular directive when modifying the data within it (eg. adding or removing data), without assigning a completely new object to that variable? Currently, I am loading a basic dataset from a JSON file usin ...

When using Angular $HTTP, CORS is supported when working with application/x-www-form-urlencoded, but there is a problem with OPTIONS 404

I have successfully implemented a Node + ExpressJS with CORS setup using this middleware. However, I am facing issues when working with POST requests. Here is what works: $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded"; ...

Issues encountered when utilizing a computed property in Typescript to organize an array

Attempting to implement Vue in a typescript single page application, I encountered a challenge where arrays needed to be displayed on screen in sorted lists. Despite the seemingly simple nature of the problem, none of the examples I came across seemed to w ...

Ways to resolve the error message "Type 'Promise<{}>' is missing certain properties from type 'Observable<any>'" in Angular

Check out this code snippet: const reportModules = [ { url: '', params: { to: format(TODAY, DATE_FORMAT).toString(), from: format(TODAY, DATE_FORMAT).toString() } }, { url: 'application1', params: { to: for ...

What is preventing the combination of brand enums in Typescript 3?

Utilizing brand enums for nominal typing in TypeScript 3 has been a challenge for me. The code snippet below demonstrates the issue: export enum WidgetIdBrand {} export type WidgetId = WidgetIdBrand & string; const id:WidgetId = '123' as Wi ...

Avoid triggering onClick events on all rows when clicking, aim for only one row to be affected per click

I have a unique situation where I have a table containing rows with a button in each row. When this button is clicked, it triggers an onClick event that adds two additional buttons below the clicked button. The Issue: When I click on a button, the onClick ...

Encountering a challenge with triggering a dialog box from an onClick event on a pie chart in Angular 8 when utilizing chart.js

I am currently using a chart.js pie chart to showcase some data. I have managed to display the required information in an alert box when a slice of the pie is clicked. However, I am now looking for a way to present this data in a dialog box instead. &a ...

"Troubleshooting a glitch encountered while making an invokeAPI call with Azure Mobile

Working on integrating my Angular App with Azure Services as the back end. Initially, I used the standard $http call: $http({ method: 'POST', url: "https://services.example.com/Api/myApi", headers : { "Content-Type" ...

Building a React Typescript service with axios functionality

When creating a service and calling it from the required functional component, there are two different approaches you can take. 1. export const userProfileService = { ResetPassword: async (userId: string) => { var response = await http.get ...

Steps for updating a property of an element in AngularJS

There is a function in my code that toggles a property value in an object, but for some reason the object does not get updated when the function runs. $scope.menuButtons = [{header: "beaded", isActive: false}, {header: "laced", isAc ...

The use of aliases is not supported by a published node module

I have a project built using create-react-app and it's utilizing react-app-rewired/react-scripts-ts. Within my tsconfig file, I've configured it as follows: baseUrl: "src", paths: { "src/*": "./*" } In many files within this project, the pa ...