Is it ok to do the $http get request on ui.router&

2020-07-09 03:26发布

I have the following code (below), they work perfectly for me and to what I need at least. But Im kind of skeptical about this, Im having a feeling that its too good to be true. Since Im struggling with $http's async behavior this helped me a lot to use the response object from the $http request globally on the controller.

I just want to know if its the right way or at least an acceptable one or should I use the conventional way of using $http get like the one on AngularJS' Documentation before I move on with my project. Answers will help me a 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;
}])

1条回答
对你真心纯属浪费
2楼-- · 2020-07-09 03:40

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.

查看更多
登录 后发表回答