Using an external variable within an internal function in TypeScript

I am facing a situation where I have a variable outside of a function that needs to be updated, but I am unable to access it using "this" as it is not reachable at that point in the code.

export class GamesDetailPage {

  details : any = {};
  type : String;
  level : Number; 
  cards : any = {}; // This is the variable I need to change

  constructor(public navCtrl: NavController, public http: HttpClient , private device: Device, private serviceProvider: ServicesProvider,     
                                            public navParams: NavParams
) {
    this.type = navParams.get('gameType');
    this.level = navParams.get('gameLevel');
  }

  ionViewDidLoad() {


    this.getCards();  // Invoking the method here  
  }


  getCards(){
    var deviceUUID = this.device.uuid;
    var platform =  this.device.platform;
    var cardsReq = {"gameType": this.type ,"gameLevel": this.level};
    var dialog = this.dialogs;

   this.serviceProvider.getCards(deviceUUID, platform, cardsReq)

    .then(function (res){
      this.cards = res;// Need to set the variable value here, but "this" is undefined
    })
    .catch(function(err){
      console.log("Error");
    })
  }
}

Answer №1

Make sure to implement the ES6 arrow function when coding. In older methods like (function(){, the reference of this is different compared to ES6 where it will...

An arrow function expression has a more concise syntax than a traditional function expression and does not have its own this

.then( 
(res) => {
      this.cards = res; // This should work correctly now
    }
)

Answer №2

Due to the fact that the outer this is overshadowed by the inner this within the function. The most direct and recommended approach is to utilize arrow functions in typescript.

To convert the lambda function, do the following:

(result) => {}

An alternative older solution involves storing this in a temporary variable:

temp = this

Then, you can refer to temp inside your lambda function.

Answer №3

When working with JavaScript, the keyword this refers to the current function being executed. However, TypeScript does some work behind the scenes to abstract this concept.

There are two main approaches you can take in dealing with this behavior.

First, you can utilize ES6 arrow functions, which will handle the scoping of this for you in TypeScript:

.then((res) => {
    this.cards = res;
})

Alternatively, you have the option to manage the scoping yourself:

getCards(){
    var _this = this;

    // Additional code

    .then(function (res){
        _this.cards = res;
    })

If you examine the transpiled code for both scenarios, you'll notice that they are very similar in nature.

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

"Extracting information from the axios header and passing it to a Vue component: A step-by-step

I am working with an axios apiClient and trying to retrieve the email stored in localStorage to use in the header of my component. I attempted to access the email by using response.headers['email'] and storing it in a variable called email, but ...

What is the best approach for implementing line coverage for object literal in Typescript Mocha unit-tests?

Lead: I am a newcomer to using typescript and writing unit tests with Mocha and Chai. Question: Can anyone provide tips on achieving 100% line coverage in unit tests for an object literal that isn't within a class? I want to avoid going static if pos ...

The term 'Buffer' is not recognized in the context of react-native

Having trouble using buffer in my react-native app (developed with the expo tool). I have a hex value representing a geography Point like this for example -> 0101000020E61000003868AF3E1E0A494046B3B27DC8F73640 and I'm attempting to decode it into l ...

Tips for creating a unique design for a form that includes a non-binary mask, inspired by bitmasks

Currently, I am in the process of creating an app using Reactjs and Material-UI. The main requirement is for users to input a mask of specific length containing various letters such as I, V, and C. In search of a suitable design pattern or solution for thi ...

Fill a form with jQuery and ajax data after it has been submitted

I'm working on a simple HTML form and I want to use Ajax to perform a lookup using a PHP file after entering data into the first field. The goal is to fetch information from an external source for the two remaining fields. <form method="post" acti ...

Directive not working on Mozilla Firefox

Currently, I have a directive set up to display an image as a background image. This works perfectly fine in Chrome and Safari, but for some reason, it doesn't seem to be functioning properly in Firefox as the background images are not showing up. Aft ...

The ASP.NET Core Web API successfully sends back a response, but unfortunately, the frontend is only seeing an empty value along with a status code of 200 (OK)

Currently, I am delving into the world of web APIs and have stumbled upon a perplexing issue that requires assistance. I have an active ASP.NET Core Web API at the backend, while at the frontend, an Angular application (running on version 15.1.5) is in pl ...

Oops! The program encountered an issue where it couldn't access the "Point" property because it was undefined. This occurred while working with openlayers 3 and jsts on

I am currently working on implementing a buffer function for some features that have been drawn on a map following this particular example. However, I am encountering the following error: ERROR TypeError: Cannot read property 'Point' of undefin ...

Submitting an extremely large string to an Express server using JS

How can a large String be efficiently sent to a Node.js Express server? On my webpage, I am using Codemirror to load files from an Express server into the editor. However, what is the most effective method for sending "the file" (which is actually a bi ...

Storing the result of parsing JSON data into a global variable

$(function() { var countFromData = 0; getReminder(); alert(countFromData); }); function getReminder() { $.getJSON("<?=base_url()?>home/leavereminder", {}, function(data) { ...

Update and republish an outdated npm package

After successfully publishing an npm package, I attempted to make an update which unfortunately resulted in some issues. It seems that I made a mistake during the build process. Since it had been a year since my last update, I have forgotten the exact step ...

Simply output the integer value

Recently, I've been working on a function that I'm trying to condense into a one-liner code for a challenge on Codewars. You can find the problem here. Here's the code snippet that I currently have: export class G964 { public static dig ...

Retrieving data from a nested object with varying key names through ng-repeat

My JSON object contains various properties with unique names: var definitions = { foo: { bar: {abc: '123'}, baz: 'def' }, qux: { broom: 'mop', earth: { tree: 'leaf', water: 'fi ...

Implementing Cross-Origin Resource Sharing (CORS) in play-framework version 2.5.x: A Step-by-Step Guide

My current challenge involves retrieving JSON data by sending a request to a Restful URL from localhost within an AngularJS-1 application. The error that I encounter is as follows: http://localhost:9000/mlm/user/all Failed to load resource: the server r ...

What is the method for prompting a save as dialog in the browser in order to save JSON data stored in memory?

As the title suggests, I am looking for a way to store JSON data in memory. I want this action to be triggered by an onclick event on a DOM object. The goal is to save the data on the user's computer as if they were downloading a file. Saving it as t ...

Having issues with the JavaScript voting system {{bindings}} returning null when clicked?

It seems like the error is not appearing in the developer tool, so it might be related to how the data is being read. Both {{upVote}} and {{downVote}} start with no value and show null when clicked, indicating that the buttons are somehow linked. I was att ...

Is there a way to obtain cookies on a Server-side component in the latest version of Next.js?

import axios from "axios"; const Api = axios.create({ baseURL: "http://127.0.0.1:5000", }); axios.defaults.headers.common["Authorization"] = cookie; In server-side environment, document.cookie is not accessible. Alternat ...

The Tab style in Mobile Angular UI does not get applied correctly when nested within an ng-repear

While working on a tabbed control with mobile-angular-ui (), I encountered an issue when trying to generate the tabs dynamically. Initially, everything looked good with the following code: <ul class="nav nav-tabs" ui-state='activeTab' ui-def ...

"Upon loading the page, I encounter JavaScript errors related to Angular's ngOnInit function. However, despite these errors,

I have a page in angular where I am loading data in the ngOnInit function. The data loads correctly and is displayed on the page, everything seems to be working fine. However, I am encountering numerous javascript errors in the console stating cannot read ...

Dynamic JavaScript Calculations Based on User Input in Real Time

I am in the process of creating a dynamic calculator that updates in real-time based on user input from a form. I have successfully implemented this feature using a sample div, but I am encountering difficulties when attempting to display the total inside ...