如何将API响应变量从通用服务传递到多个控制器。
我正在通过以下API响应获取数据。
$scope.responseData = reply.data;
我仅用于ApiService
中的API。在这里,我使用的是我在应用程序中使用的任何API。
API服务:
app.service('apiService', ['$http', function ($http) {
this.getData = function (userId) {
return $http.get('myapi' + userId);
};
}]);
常用服务:
app.service('commonService', ['$window', function ($window) {
apiService.getData($scope.UserId).then(function (reply) {
$scope.responseData = reply.data;
// ...
});
});
控制器1、2、3:
app.controller('firstController', ['apiService', 'commonService',function (apiService, commonService) {
// ...
$scope.responseData.forEach(function (data) {
// do something
})
}]);
app.controller('secondController', ['apiService', 'commonService',function (apiService, commonService) {
// ...
$scope.responseData.forEach(function (data) {
// do something
})
}]);
app.controller('thirdController', ['apiService', 'commonService',function (apiService, commonService) {
// ...
$scope.responseData.forEach(function (data) {
// do something
})
}]);
我在控制器中一次又一次地使用相同的循环($scope.responseData
),所以我的应用程序变慢了。如何编写一次代码并在多个控制器中使用它?谁能给我解释一下如何解决这个问题?
答案 0 :(得分:0)
您可以使用SELECT blog.bid,blog.btitle,COUNT(likes.lid) AS likecnt,COUNT(comment.comid) AS commentcnt FROM blog,likes,comment WHERE blog.bid=likes.bid AND blog.bid=comment.bid GROUP BY blog.bid
类似的东西:
$rootScope.$broadcast(/* ... */)
在您的控制器中,您可以编写:
app.service('commonService', ['$window', '$rootScope', function ($window, $rootScope) {
apiService.getData($scope.UserId).then(function (reply) {
$scope.responseData = reply.data;
$rootScope.$broadcast('onGetData', {value: reply.data});
$scope.responseData.forEach(function (data) {
console.log(data);
});
$timeout(function () {
$scope.responseData.forEach(function (data) {
if (data.Category == 'A') {
console.log("A");
} else if (data.Category == 'B') {
console.log("B");
} else if (card.Category == 'C') {
console.log("C");
}
})
});
});
});