Javascript AngularJS中的模拟服务
我对AngularJS是新手。我在做一个AngularJS项目。我的项目将使用RESTAPI,该API将在Javascript AngularJS中的模拟服务,javascript,angularjs,Javascript,Angularjs,我对AngularJS是新手。我在做一个AngularJS项目。我的项目将使用RESTAPI,该API将在http://www.myserver.com/customers。该API尚未构建。根据我的理解,我可以假装反应,这样我就可以继续发展。然而,我不明白如何做到这一点。目前,我有以下代码: index.js myApp.controller('MyController', function($scope, customerService) { ... $scope.getCustom
http://www.myserver.com/customers
。该API尚未构建。根据我的理解,我可以假装反应,这样我就可以继续发展。然而,我不明白如何做到这一点。目前,我有以下代码:
index.js
myApp.controller('MyController', function($scope, customerService) {
...
$scope.getCustomers = function() {
customerService.getCustomers.then(
function(res) {
console.log('customers retrieved from server!');
console.log(res);
},
function() {
console.log('there was an error.');
}
);
};
...
});
myApp.service('customerService', function($http, $q) {
this.getCustomers = function() {
return $http.get('http://www.myserver.com/customers');
};
});
customerService.js
myApp.controller('MyController', function($scope, customerService) {
...
$scope.getCustomers = function() {
customerService.getCustomers.then(
function(res) {
console.log('customers retrieved from server!');
console.log(res);
},
function() {
console.log('there was an error.');
}
);
};
...
});
myApp.service('customerService', function($http, $q) {
this.getCustomers = function() {
return $http.get('http://www.myserver.com/customers');
};
});
如何模拟RESTAPI调用的结果
谢谢大家! 您可以返回使用示例数据解析的承诺
myApp.service('customerService', function($http, $q) {
this.getCustomers = function() {
var data = [{id: 1, value: 'foo'}, {id: 2, value: 'bar'}];
return $q.when(data);
};
});
然后,当后端准备就绪时,您可以将服务更改为使用$http
,展开响应并从服务返回数据(您可能还需要添加错误处理)。应该不需要更改调用服务的代码
myApp.service('customerService', function($http, $q) {
this.getCustomers = function() {
return $http.get('http://www.myserver.com/customers')
.then(function(response) {
return response.data;
});
};
});
angular有一个模拟服务和一些带有$httpBackendService的东西。但我还没有弄明白,我只是在控制器中使用占位符对象。您是试图模拟服务(测试控制器)还是模拟$http调用(测试服务)?