Reputation: 401
I have an application with a parent controller called DashboardCtrl, and multiple child controllers (DashboardBuyerCtrl, DashboardSellerCtrl...)
I'd like to be able to share the results of an HTTP request between the different controllers. At the moment, I'm executing my HTTP request in every controller, but I think that this is not ideal performance wise. I've read that I should use service, but I'm stuck here.
can anyone help?
Thanks
Upvotes: 0
Views: 60
Reputation: 4154
Using services is, in general, a good practice because helps you to organize and share the code across your application, I've created a small app to showcase how services could be created and reused in controllers:
var app = angular.module('testApp', []);
app.controller('ctrlA', function($scope, getIp) {
getIp().then(function(resp) {
$scope.data = resp.data.origin;
});
});
app.controller('ctrlB', function($scope, getIp) {
getIp().then(function(resp) {
$scope.data = resp.data.origin;
});
});
app.service('getIp', function($http) {
return function() {
return $http.get('https://httpbin.org/ip');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testApp">
<div ng-controller="ctrlA">
First controller
<p>IP: {{data}}</p>
</div>
<div ng-controller="ctrlB">
Second controller
<p>IP: {{data}}</p>
</div>
</div>
Regarding performance, I'd suggest using caching option if content is not being updated frequently(or not updated at all), like so:
$http({
url: '...',
method: 'GET',
cache: true
});
This will save request's response for future use.
You can read more about services in the official documentation.
Upvotes: 1