Javascript 如何在es6中正确访问AngularJS服务
我试图访问我的服务的属性,我认为我将服务注入类的方式有问题。运行我的应用程序时,我收到以下错误消息 angular.js:13424 ReferenceError:CouponsService未定义 在CoupOnComponent.onInit(coupons.controller.js:13) 服务 控制器Javascript 如何在es6中正确访问AngularJS服务,javascript,angularjs,angular-services,Javascript,Angularjs,Angular Services,我试图访问我的服务的属性,我认为我将服务注入类的方式有问题。运行我的应用程序时,我收到以下错误消息 angular.js:13424 ReferenceError:CouponsService未定义 在CoupOnComponent.onInit(coupons.controller.js:13) 服务 控制器 (函数(){ 类耦合组件{ 构造函数($state,CouponsService){ this.test='hello'; this.state=$state; this.coupon
(函数(){
类耦合组件{
构造函数($state,CouponsService){
this.test='hello';
this.state=$state;
this.couponParams={};
}
$onInit(){
console.log(CouponsService);
}
processParams(){
如果(!this.couponParams.amount | | this.couponParams.amount问题在于变量的作用域。将其注入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
}
还建议您使用构建工具,使注入工作得更好。您必须使用注入服务来装饰您的类
加:
(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
});
})();
class CouponsComponent {
constructor($state, CouponsService) {
this.test = 'hello';
this.state = $state;
this.CouponsService = CouponsService;
this.couponParams = {};
}
$onInit() {
console.log(this.CouponsService);
}
// Rest of class
}
CouponComponent.$inject = ['$state', 'CouponService'];