如何在 es6 中正确访问 AngularJS 服务

How to properly access AngularJS service in es6

我正在尝试访问我的服务的属性,我认为我将服务注入 class 的方式有问题。当 运行 我的应用

时,我收到以下错误消息

angular.js:13424 ReferenceError: CouponsService is not defined

at CouponsComponent.$onInit (coupons.controller.js:13)

...

服务

angular.module('couponGeneratorApp')
  .service('CouponsService', function () {
    // AngularJS will instantiate a singleton by calling "new" on this function
    this.amount_type = null;
    this.amount = null;
    this.has_min = null;
    this.min_order = null;
  });

控制器

(function() {

    class CouponsComponent {
        constructor($state, CouponsService) {
            this.test = 'hello';
            this.state = $state;

            this.couponParams = {};
        }

        $onInit() {
            console.log(CouponsService);
        }

        processParams() {
            if (!this.couponParams.amount || this.couponParams.amount <= 0) {
                alert('Enter a valid amount');
            } else if (this.couponParams.has_min && (!this.couponParams.min_order || this.couponParams.min_order < 0)) {
                alert('Enter a valid min order');
            } else {
                CouponsService.amount_type = this.couponParams.amount_type;
                CouponsService.amount = this.couponParams.amount;
                CouponsService.has_min = this.couponParams.has_min;
                if (CouponsService.has_min) CouponsService.min_order = this.couponParams.min_order;
                this.state.go('coupons.login');
            }
        }
    }


    angular.module('couponGeneratorApp')
        .component('couponsForm', {
            templateUrl: 'app/coupons/form.html',
            controller: CouponsComponent
        });

    angular.module('couponGeneratorApp')
        .component('couponsLogin', {
            templateUrl: 'app/coupons/login.html',
            controller: CouponsComponent
        });
})();

问题出在变量的范围上。当您将其注入 ES6 class 时,构造函数方法不会使该变量可用于所有其他方法。因此,就像您将 $state 设置为 this.$state 一样,您需要对其他方法将使用的任何注入服务执行相同的操作。

class CouponsComponent {
    constructor($state, CouponsService) {
        this.test = 'hello';
        this.state = $state;
        this.CouponsService = CouponsService;

        this.couponParams = {};
    }

    $onInit() {
        console.log(this.CouponsService);
    }

    // Rest of class
}

还建议使用 ngAnnotate,这样您的构建工具可以帮助更好地进行注入。

您必须使用可注射服务来装饰您的 class。

添加:

CouponComponent.$inject = ['$state', 'CouponService'];