undefined不是Angular.js服务中的对象 [英] undefined is not an object in Angular.js service
本文介绍了undefined不是Angular.js服务中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的service
angular.module('App')
.factory("AppService", [function() {
var _admin;
return {
get admin() {
return _admin;
},
};
}]);
在我的controller
中,我像这样使用它:
In my controller
i am using it like this:
$scope.show = function(){
return AppService.admin === 0 || (AppService.admin !== 0 && AppService.admin === true);
};
当我尝试测试function
时,出现如下错误:
When i am trying to test the function
, i am getting an error like below:
it('calls the showAutoPay method', function () {
$scope.show();
expect($scope.show).to
.have.been.calledOnce;
expect(service.admin).to.not.equal(null);
assert.equal(service.admin, '0');
});
我也不确定如何模拟具有get
和set
方法的AppService
.
I am also not sure how to mock the AppService
which has the get
and set
methods.
推荐答案
我认为这是您要寻找的:
I think this is what are you looking for:
(function() {
"use strict";
angular.module('app', [])
.controller('mainCtrl', function(AppService) {
var vm = this;
vm.service = AppService;
vm.service._admin = 10;
vm.random = function() {
vm.service._admin = Math.floor(Math.random() * 5);
console.log('AppService obj => ', AppService._admin);
};
})
.factory('AppService', function() {
var admin;
this.appService = {
get _admin() {
return admin;
},
set _admin(val) {
admin = val;
}
};
return this.appService;
});
})();
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl as main">
<button type="button" ng-click="main.random()">Change value</button>
<span ng-bind="main.service._admin"></span>
</body>
</html>
这篇关于undefined不是Angular.js服务中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文