javascript - Is it ok to do the $http get request on ui.router's resolve in angularjs? -
i have following code (below), work me , need @ least. im kind of skeptical this, im having feeling true. since im struggling $http
's async behavior helped me lot use response object $http
request globally on controller.
i want know if right way or @ least acceptable 1 or should use conventional way of using $http
1 on angularjs' documentation before move on project. answers me lot. thank you.
$stateprovider
$stateprovider .state('test', { url: '/test', templateurl: 'partial.template.html', resolve : { foo : function($http) { return $http({ method: 'get', url: '/api/something' }); }, bar : function($http) { return $http({ method: 'get', url: '/api/something' }); }, }, controller: 'maincontroller', })
controller
.controller('maincontroller',['$scope', 'foo', 'bar', function($scope, foo, bar){ $scope.fooobj = foo; $scope.barobj = bar; }])
i think best usecase ui-router resolve.
anyway i'd prefer wrap http call services , call services resolve instead of using $http directly.
this may :
app.service('fooservice',function($http){ var service={}; service.getfoo = function(){ return $http({ method: 'get', url: '/api/something' }); } return service; });
thanks can call method around application (and centralize @ same time).
in controller :
app.controller('mycontroller', function($scope, fooservice) { $scope.controllername = "mycontroller"; fooservice.getfoo().success(function(foo){ $scope.foo = foo }); });
in resolve :
$stateprovider .state('test', { url: '/test', templateurl: 'partial.template.html', resolve : { foo : function(fooservice) { return fooservice.getfoo(); }, }, controller: 'mycontroller', })
go on approach, you're on way.
hope helped.
edit : built plunker add concrete exemple of theses methods.
Comments
Post a Comment