如何正确访问es6中的AngularJS服务
How to properly access AngularJS service in es6
我正在尝试访问服务的属性,我认为将服务注入类的方式有问题。我在运行应用时收到以下错误消息
angular.js:13424 ReferenceError:CouponsService未定义
CouponsComponent$onInit(优惠券.控制器.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类时,构造函数方法不会使该变量对所有其他方法都可用。因此,就像您将$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,这样您的构建工具可以帮助更好地进行注入。
您必须使用可注入服务来装饰您的类。
添加:
CouponComponent.$inject = ['$state', 'CouponService'];
相关文章:
- 在AngularJS服务中使用$http回调
- AngularJS 1.5.x服务未正确绑定,并且未在控制器中更新
- 使用AngularJS服务未获取数据
- 为什么Angularjs服务返回的是字符数组而不是对象数组
- AngularJS服务函数调用另一个函数
- AngularJS服务(更新/保存)
- 如何在打字稿的控制器中添加 angularjs 服务
- AngularJS 服务注入器错误
- 如何正确地通过angularjs服务连接到套接字
- 如何使用angularjs服务将表单参数传递给Rest
- 如何点击按钮调用angularJs服务
- angularjs服务生成数据后,我该如何停止它
- 我一直在获取angularjs服务不是函数错误(LoginService.login不是函数)
- 如何正确访问es6中的AngularJS服务
- 在多个控制器中使用AngularJs服务
- 如何处理AngularJS服务中的回调
- 如何访问回调函数之外的异步angularjs服务数据
- AJAX加载JSON数据并将其存储在angularjs服务中
- 获取AngularJS服务中TextArea的值
- 在Angularjs服务中为返回对象引用的http请求提供的数据构建简单的缓存