创建一个自定义 http 服务,该服务将请求外部 JSON 文件



我有一个http服务,它将调用外部json文件并将其加载到网格中。

我的问题是我需要创建一个自定义的http服务,以便我可以在不同的控制器中使用相同的服务。该自定义服务的功能应相同(请求外部 Json 文件(

$http.get('../JSON/permanentEmployees.json').
success(function(data, status, headers, config) {
$scope.masterArray = data;
}).
error(function(data, status, headers, config) {
$scope.errorMessage = "Requested grid data file does not exist";
});

这是我目前的http服务。任何帮助将不胜感激。请仅使用角度

将代码包装在工厂中并使用它。我认为在这种情况下最好使用工厂,请参阅此处。附言无法创建对 JSON 的请求的模型,请检查您的 JSON。

JSFiddle:这里

app.factory('customHTTPService', function($http){
return {
getRequest: function(url) {
return $http.get(url).
success(function(data, status, headers, config) {
return {data: data, errorMessage: "Success"};
}).
error(function(data, status, headers, config) {
return {data: "", errorMessage: "Requested grid data file does not exist"};
});
} 
}
});

在控制器中你可以做

app.controller('MyController', function MyController($scope, customHTTPService) {
$scope.data = customHTTPService.getRequest('../JSON/permanentEmployees.json').data;
});    

最新更新