What is the best way to reach into the properties of a JavaScript class while working within a promise? (Utilizing ES6 instead of self-exec

Currently, I am utilizing ES6 classes in order to build an angular controller. My goal is to use promises for loading my products. Upon calling getProducts, the data returns with the required information. However, there seems to be an issue as the this within this.products = results appears to be undefined resulting in a "Cannot set property 'products' of undefined" error. How can I effectively access properties from inside the 'then' function?

export class ProductController {  
  constructor (Product) {
    'ngInject';

    this.ProductService = Product;
    this.products = [];    
    this.getProducts();
  }

  getProducts() {
    let self = this; // Assigning 'this' to a variable that will maintain its reference

      this.ProductService
        .find()
        .$promise
        .then(function (results) {
            self.products = results; // Accessing 'products' through the variable 'self'
        }, function (results) {
            console.log(results);
        });
  }
}

Answer №1

Disclaimer: I'm not extremely well-versed in ES6, so this method may be outdated.

One way I handle issues with the this keyword is by assigning it to a different variable:

fetchData() {
  let that = this
  this.DataService
    .retrieve()
    .$promise
    .then(function (data) {
        that.info = data;
    }, function (error) {
        console.log(error);
    });
}

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

Having trouble adjusting the refresh timer based on user focus with setTimeout

For the past few days, I've been utilizing an ajax call to dynamically refresh specific elements of my webapp every 5 seconds. The implementation with setInterval(refreshElements, 5000) worked perfectly fine. However, now I am considering whether the ...

Tic Tac Toe is not functioning properly

Hey there! Can someone please help me figure out what's going on? I'm trying to create a Tic Tac Toe game, but instead of using "O" and "X" to mark the fields, I want to use different colors. Specifically, one player should be able to mark with b ...

Map data stored offline with the use of indexeddb and JSON documents

Looking to create an offline map using topoJSON and openlayers for map generation. I stored the JSON data in indexeddb as a blob and tried converting it back to JSON. Everything was going smoothly until I encountered an error while converting the blob bac ...

As the text is being selected within a react-rnd, once the selection extends outside of the draggable component, the selected text will automatically adjust

I've encountered an issue with a draggable textarea created using react-rnd. The problem arises when I try to select text within the textarea, and accidentally move my cursor outside of the react-rnd component, causing the selection to change unexpect ...

Save the name and assigned value of a Button into a specific row within a MySQL table

I've been stuck on this issue for 3 days and it's really starting to frustrate me. It seems like a simple problem, but being a beginner, I just can't figure it out. I want to utilize the onclick function of a button to extract two specific ...

What is the process for retrieving an object from a node.js server using JSON.stringify() in a JavaScript file?

Looking to organize my code, I want to separate the JavaScript from my page and link it through a file instead of having it embedded within script tags. The issue arises when I receive a "SyntaxError: expected expression, got '<' " in Firefox ...

AngularJS's ng-click function seems to be malfunctioning

Currently, I am in the process of learning angularJS with the help of the book titled "Learning Web Development with Bootstrap and AngularJs." One challenge I am facing is creating a ng-click functionality for a button in my project. Unfortunately, when I ...

Ways to ensure certain code is executed every time a promise is resolved in Angular.js

Within my Angular.js application, I am executing an asynchronous operation. To ensure a smooth user experience, I cover the application with a modal div before initiating the operation. Once the operation is complete, regardless of its outcome, I need to r ...

I am puzzled as to why the JSON response is visible in the browser but cannot be forwarded to the Ajax callback function, causing the page to remain on the initial request page

Currently, I am in the process of developing a web application that utilizes AJAX and servlet. My main focus right now is creating a functional login page for the application. Although the servlet successfully generates a response in JSON format, the issu ...

Replace async/await with Promise

I want to convert the async/await code snippet below: const mongoose = require('mongoose') const supertest = require('supertest') const app = require('../app') const api = supertest(app) test("total number of blogs" ...

Utilizing ReactJs refs to set focus on an input element

Exploring the use of refs in ReactJs to focus a textbox from a button click. Encountering the following error message: bundle.js:114 Uncaught TypeError: Cannot read property 'focus' of undefined Check out the Source Code below: class FocusTex ...

Tabulator and its convenient scrollable column feature allows for easy navigation

In case my tabulator column is exceeding its length, is there a way to enable scroll functionality for that specific column? Although the resizable rows feature permits users to resize and view all the content, can a scrollbar be implemented exclusively ...

Controllers should have filters implemented as a best practice

Hello, I am struggling to integrate a filter into my controller. Below is my controller code along with the filter that I created a few days ago. Any help would be greatly appreciated! angular.module('tickets').controller('TicketsControlle ...

Is there a way to deactivate the Edge mini menu while selecting text in a React application?

I have recently been working on a React web application and managed to create a specialized text selection menu. However, I am facing a challenge in programmatically disabling the default text selection mini menu in React. The image attached illustrates bo ...

Unable to retrieve JSON information using AJAX

Trying to retrieve data from the server without refreshing the page using AJAX. The issue is that the data appears as text rather than in JSON format. Here is my code: $.ajax({ type: "GET", url: "http://localhost:8080/search?key=" + QUERY + "", ...

Creating a Javascript countdown timer that does not involve displaying the

I stumbled upon this code on a website, but there's one tweak I'd like to make. Unfortunately, I can't seem to figure it out myself, so I'm reaching out for some help. What I want to achieve is removing the year from the date so that th ...

Looking for Precise Matching within JSON Using JavaScript

I've been experimenting with creating a form that submits data and then checks it against a JSON array to see if there's a matching object already present. Here is a snippet of my JSON data for reference: [ { "ASIN":"B0971Y6PQ3 ...

Fetching data from a Django view using a JavaScript AJAX POST call

Utilizing Javascript for an asynchronous request to a Django View, I am able to successfully receive data from the POST request. However, I am encountering issues with returning a confirmation message that the process was successful. Despite expecting xhtt ...

Switching between API requests through a live feed

Hey there: import Rx from 'rxjs'; function mockApi(endpoint, time, response) { return new Rx.Observable(observer => { console.log(`${endpoint}: Request initiated.`) let active = true; const id = setTimeout(() => { cons ...

Working with JavaScript and making AJAX calls to interact with PHP backend

Having trouble with this code, it's not working as expected. I want to pass the value when I select an option from the dropdown menu, process the data using onChange event and display the value in the tag. <label for="headmark" class="lbl-ui selec ...