Is it ok to do the $http get request on ui.router's resolve in angularjs?

泄露秘密 提交于 2019-12-04 06:19:46

I think this is probably the best usecase for a ui-router resolve.

Anyway i'd prefer to wrap my http call into services and call this services into the resolve instead of using $http directly.

This may look like this :

app.service('FooService',function($http){
  var service={}; 
  service.getFoo = function(){
      return $http({
                method: 'GET',
                url: '/api/something'
             });
  }
  return service;
});

Thanks to that you can call this method all around your application (and centralize it at the same time).

In controller :

app.controller('MyController', function($scope, FooService) {
    $scope.controllerName = "MyController";
    FooService.getFoo().success(function(foo){
        $scope.foo = foo
    });
});

In a resolve :

$stateProvider
.state('test', {
    url: '/test',
    templateUrl: 'partial.template.html',
    resolve : {
        foo : function(FooService) {
            return FooService.getFoo();
        },
    },
    controller: 'MyController',
})

Go on with this approach, you're on a good way.

Hope it helped.

EDIT : Built a plunker to add a concrete exemple of theses methods.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!