Currently, I am storing my API response in a $scope variable within my main controller. However, I realize that rewriting this code in each controller is slowing down my application. I am considering moving it to a service file and using it across all controllers.
MainController.js :
$scope.UserId = reply.split('UserId=').pop().toUpperCase();
apiService.getResponseData($scope.UserId).then(function(reply) {
$scope.responseData = reply.data;
$timeout(function() {
reply.data.forEach(function(card) {
if (card.Category == 'Apple') {
console.log("Apple");
} else if (card.Category == 'Google') {
console.log("Google");
} else if (card.Category == 'Microsoft') {
console.log("Microsoft");
} else if (card.Category == 'Amazon') {
console.log("Amazon");
}
});
});
});
This is my MainController. How can I refactor this code into a service file?
CommonService.js :
app.service('commonService', ['$timeout', '$rootScope', 'apiService',
function($timeout, $rootScope, apiService) {
this.app = function($scope) {
$scope.UserId = reply.split('UserId=').pop().toUpperCase();
apiService.getResponseData($scope.UserId).then(function(reply) {
$scope.responseData = reply.data;
$timeout(function() {
reply.data.forEach(function(card) {
if (card.Category == 'Apple') {
console.log("Apple");
} else if (card.Category == 'Google') {
console.log("Google");
} else if (card.Category == 'Microsoft') {
console.log("Microsoft");
} else if (card.Category == 'Amazon') {
console.log("Amazon");
}
});
});
});
return app;
};
}
]);
It's important to note that $scope won't work in the service file. Can someone assist me in modifying the code above so that it can be used from the service to multiple controllers?