我在角度服务中调用了一些方法,如下所示:
someService.getXXXX($scope);
someService.getYYYY($scope);
//. . . . x 30
该服务如下所示,有许多重复的方法:
this.getXXXX = function ($scope) {
return $http({
method: "GET",
url: "http://localhost:51461/api/XXXX",
headers: { 'Content-Type': 'application/json' }
}).success(function (data) {
$scope.XXXX = data;
console.log(data);
}).error(function (data) {
console.log(data);
});
};
this.getYYYY = function ($scope) {
return $http({
method: "GET",
url: "http://localhost:51461/api/YYYY",
headers: { 'Content-Type': 'application/json' }
}).success(function (data) {
$scope.YYYY = data;
console.log(data);
}).error(function (data) {
console.log(data);
});
};
除了XXXX
之外,我其中有30个是完全相同的。
所以我不能把它减少到像这样的单个函数吗?
someService.getWebService("XXXX", $scope.XXXX);
someService.getWebService("YYYY", $scope.YYYY);
// . . .
this.getWebService = function (url, outVariable) {
return $http({
method: "GET",
url: "http://localhost:51461/api/" + url,
headers: { 'Content-Type': 'application/json' }
}).success(function (data) {
outVariable = data;
console.log(data);
}).error(function (data) {
console.log(data);
});
};
它似乎正在工作,因为我正在访问我的Web服务断点,我的角度浏览器工具显示正在填充的对象。但该模型似乎没有更新/应用。
我还尝试过每次传入$ scope,只是在$scope.$apply();
之后使用outVariable = data;
,我收到错误消息说已经在运行。
答案 0 :(得分:3)
原因
someService.getWebService("XXXX", $scope.XXXX);
不起作用(假设xxxx是对象引用)是因为您正在传递对函数的引用。您可以更改引用的内容而不是引用本身。
同时传递$scope
对象是一种不好的做法。
在处理promise时,更好的机制是使用promise api,并从服务调用中返回promise,并在控制器中进行赋值。
this.getYYYY = function () {
return $http({
method: "GET",
url: "http://localhost:51461/api/YYYY",
headers: { 'Content-Type': 'application/json' }
});
};
并在控制器中执行
$scope.YYYY= service.getYYYY().then(function(data) { $scope.YYYY=data;});
答案 1 :(得分:0)
getWebService的替代方法是注册并生成函数。
var genEndpoint = function (endpoint) {
return function () {
return $http({
method: "GET",
url: "http://localhost:51461/api/" + endpoint,
headers: { 'Content-Type': 'application/json' }
});
};
};
this['get'+ XXX] = genEndpoint(XXX)