0

I am using ES6 classes to create an angular controller. I am trying to use promises to load my products. When I call getProducts the results comes back with the data I need, however the this in this.products = results is undefined and I get "Cannot set property 'products' of undefined". How can I access the properties from inside of then?

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

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

    getProducts() {
      this.ProductService
        .find()
        .$promise
        .then(function (results) {
            this.products = results;
        }, function (results) {
            console.log(results);
        });
  }
}
Nico
  • 1,094
  • 13
  • 17
  • 3
    one way is to use arrow `=>` functions ... so `.then(results => this.products = results, results => console.log(results));` – Jaromanda X Feb 25 '16 at 02:59
  • I tried to replace function (results) { this.products = results; } with (results) => this.products = results with no luck – Nico Feb 25 '16 at 03:00
  • Arrow functions are the way to go here. But notice that you actually shouldn't write asynchronously received data to instance properties - just store the promise itself in the property and many things will be easier. – Bergi Feb 25 '16 at 03:07
  • your issue is elsewhere then - do you get any errors ion your console? – Jaromanda X Feb 25 '16 at 03:07
  • @Bergi - that sort of pattern seems common in angularjs – Jaromanda X Feb 25 '16 at 03:08
  • @JaromandaX using the arrow functions did in fact fix the problem – Nico Feb 25 '16 at 03:50

1 Answers1

3

Disclaimer: I'm not incredibly familiar with ES6, so this may be an outdated approach.

My general approach to avoiding issues with this is to rename it:

getProducts() {
  let self = this
  this.ProductService
    .find()
    .$promise
    .then(function (results) {
        self.products = results;
    }, function (results) {
        console.log(results);
    });
}
Ryan Heathcote
  • 836
  • 8
  • 19