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

Is there a way to automatically collapse all the collapsible elements within the accordion when closing it?

I came across a similar topic on Stack Overflow about closing all children accordions when the parent accordion is closed, which seems to address my issue. Currently, I am using Bootstrap 4 and struggling to modify the code from the other topic to ensure ...

Using QML to assign global properties by invoking imported JavaScript functions

Utilizing the Universal style in my QtQuick application, I am seeking to implement a ColorDialog for adjusting the accent color. My current setup looks like this: ColorDialog { id: accChooser title: "Please choose a color" onAcce ...

Unexpected results occur when accessing data in $uibModal.open() within Angular JS causing it to

Here is the code snippet that is causing the issue of returning undefined items in AngularJS: App.js code console.log('single page application script is working'); var myApp = angular.module("demoApp", ["ngRoute", 'ui.bootstrap',&apos ...

Using HTML and CSS to stack a DIV on top of another using z-index

I have 3 main layers on my website: 1) The main view with elements inside (#views in jsbin) - BOTTOM LAYER 2) An overlay (with a white background opacity of .8 #overlay in jsbin) - MIDDLE LAYER 3) A context menu (#contextmenu in jsbin) - TOP LAYER Wh ...

Tips for efficiently awaiting outcomes from numerous asynchronous procedures enclosed within a for loop?

I am currently working on a search algorithm that goes through 3 different databases and displays the results. The basic structure of the code is as follows: for(type in ["player", "team", "event"]){ this.searchService.getSearchResult(type).toPromise ...

Is there a way to manipulate a website's HTML on my local machine using code?

I am currently working on a project to create a program that can scan through a website and censor inappropriate language. While I have been able to manually edit the text using Chrome Dev tools, I am unsure of how to automate this process with code. I ha ...

Making an API request using jQuery

I am currently working on creating a .js file that will send data to an external API, wait for a response, and then interpret the results. The external API I am using is XML-based and requires an HTTPS Post request with the XML content in the body (content ...

Is the 'match()' method available in node.js? If it is, what is the proper syntax to use it?

I attempted to utilize the .match() method in node.js, but encountered an error stating that has no method 'match'. Here is the section of code where I invoke the method: fs.readFile('proxy.txt', function (err, data) { if (data.mat ...

Place a call directly from the webpage

Is there a way to initiate a phone call using JavaScript? I've tried the code below: document.location.href = "tel:15555551212" While this code takes me to the dial screen of the mobile application, I actually want to place the call directly. Any ...

VueJS 3 is in the process of loading dynamic assets

I am facing an issue with loading and displaying images dynamically from the assets folder in my Vue.js project. The code I have written does not seem to work as expected: <img :src="getSource(data.thumbnail)" :alt="data.name"/> ...

Guide on attaching an onclick event to a button created with a string in Next.js?

<div onClick={(event) => this.addToCart(event)}> <ReactMarkdownWithHtml children={this.props.customButton} allowDangerousHtml /> </div> In my current situation, I am facing an issue with the code above. The button is being rendered ...

Unexpected state being returned by Vuex

I am encountering an issue with a pop-up modal that is not behaving as expected. The condition for the pop-up to appear is if the user has no transactions, which is determined by checking the length of the depositHistory array. If the length is greater tha ...

A guide on implementing radio buttons in Angular 2 and sending the selected value via a HTTP post request

As a newcomer to Angular 2, I am struggling with the following code: Here is my HTML <form action="POST" (submit)="register()" class="aa-login-form"> <input type="radio" [(ngModel)]="gender" name="sex" value="MALE"> Male <input ...

Due to a glitch in the firebase cloud function, the payment is not going through

I have developed a react-redux application with Firestore as the database and now I want to integrate Firebase Cloud Functions to handle Stripe payments. Here is how it's set up: Below is the action method for checkout, which processes token and amo ...

Transfer a file to Amazon S3 using the Microsoft Office Add-In

I am working on developing a JavaScript Microsoft Office add-in that allows users to save a document to an S3 bucket. However, I have not been able to find a way to achieve this. Has anyone managed to successfully make this work before? ...

Showing nested arrays in API data using Angular

I would like to display the data from this API { "results": [ { "name": "Luke Skywalker", "height": "172", "mass": "77", & ...

Understanding the unpredictability of A-Sync in Node.js/Express: Why does it appear to operate in a non-linear fashion?

Recently, I delved into the world of Node.js/Express and encountered asynchronous calls that must complete before moving on. My code features three different endpoints that need to be hit. Considering the asynchronous nature, I attempted to structure my c ...

modify the final attribute's value

Hello I've been using skrollr js to create a parallax website. However, the issue arises when determining the section height, as it depends on the content within. My goal is to locate the last attribute and adjust the number value based on the section ...

The header remains unchanged even after verifying the user's login status

Currently, I am using Angular 11 for the front-end and Express for the back-end. I am facing an issue with determining if a user is logged in so that I can display the correct header. Even after logging in and setting a cookie in the browser upon redirecti ...

Button Fails to Respond on Second Click

I have a button that triggers a JavaScript function. This function, in turn, initiates two sequential AJAX calls. Upon completion of the first call, it performs some additional tasks before proceeding to the second AJAX call. The button functions correctl ...