我很确定我遵守所有规则:
这是fiddle
angular.module('app', function($httpProvider, $locationProvider, MockServiceProvider) {
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$locationProvider.html5Mode(false);
MockServiceProvider.enableMocks(true);
})
.provider('MockService',['$http', '$q', function ($http, $q) {
this.mocksEnabled = false;
this.enableMocks = function(val) {
mocksEnabled = val;
};
this.$get = function() {
var _mock_getNext = function() {
return {
'status' : {
'type': 'OK',
'msg': null
},
'data': {
'id': 123456789
}
};
};
return {
getData : function() {
if(mocksEnabled) {
return _mock_getNext;
} else {
return "Real Data";
}
}
};
};
}])
.controller('Main', function(MockService) {
$scope.maybe_mock_data = MockService.getData();
});
答案 0 :(得分:2)
提供程序的$http
和$q
注入应位于提供程序的$get
方法上,而不是提供程序的构造函数上。
小提琴:http://jsfiddle.net/pvtpenguin/UAP29/1/
.provider('MockService',function () {
this.mocksEnabled = false;
this.enableMocks = function(val) {
mocksEnabled = val;
};
this.$get = ['$http', '$q', function($http, $q) {
var _mock_getNext = function() {
return {
'status' : {
'type': 'OK',
'msg': null
},
'data': {
'id': 123456789
}
};
};
return {
getData : function() {
if(this.mocksEnabled) {
return _mock_getNext;
} else {
return "Real Data";
}
}
};
}];
})
其他小问题:
$scope
未注入控制器getData
功能中,mocksEnabled
必须是this.mocksEnabled