tobbe
tobbe

Reputation: 1807

Calling angular service from ES6 class method

(Im using Babel to be able to use ES6)

When I call addConfigurationToCart() I get:

ReferenceError: Order is not defined.

But in the constructor I don't. Why is that? I get the same error if I add Order as a parameter to addConfigurationToCart

class ConfigCtrl {
    constructor($state, api, Order) {
        this.current = Order.current;
    }

    addConfigurationToCart() {
        Order.saveConfiguration();
        $state.go('order');
    }
}

Upvotes: 1

Views: 761

Answers (3)

alexk
alexk

Reputation: 1528

controller: class {
    constructor($http, Restangular, $state) {
        Object.assign(this, {$http, Restangular, $state});
    }
    doIt() {
       // use this.$http, this.Restangular & this.$state freely here
    }
}

Upvotes: 1

Estus Flask
Estus Flask

Reputation: 222369

constructor and addConfigurationToCart functions have different scopes (in JS sense), and sure, the variable from one scope isn't available in another, unless the variable is assigned to either this property or the variable from parent scope.

Private variables are still aren't there in ES2015+, but there are some workarounds to do that.

The most obvious way is using local variables:

let $state, api, Order;

class ConfigCtrl {
  static $inject = ['$state', 'api', 'Order'];

  constructor(...args) {
    [$state, api, Order] = [...args];
    // ...
  }

  addConfigurationToCart() {
    Order.saveConfiguration();
    // ...
  }
}

And more idiomatic approach that successfully provides private variables within class:

const [$state, api, Order] = [Symbol(), Symbol(), Symbol()];

class ConfigCtrl {
  static $inject = ['$state', 'api', 'Order'];

  constructor(...args) {
    [$state, api, Order].forEach((v, i) => this[v] = args[i]);
    // ...
  }

  addConfigurationToCart() {
    this[Order].saveConfiguration();
    // ...
  }
}

Upvotes: 1

m.brand
m.brand

Reputation: 658

You have to make the Service public to the rest of your class.

class ConfigCtrl {
  constructor($state, api, Order) {
      ...
      this.Order = Order;
  }

  addConfigurationToCart() {
      this.Order.saveConfiguration();
      ...
  }
}

Upvotes: 1

Related Questions