在 angularjs 中对 ui.router 的解析执行 $http get 请求是否可以?

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

我有以下代码(下方),它们非常适合我,至少满足我的需要。但我对此持怀疑态度,我觉得它好得令人难以置信。由于我在 $http 的异步行为中苦苦挣扎,这对我在控制器上全局使用来自 $http 请求的响应对象有很大帮助。

我只想知道它是否正确或至少是可以接受的方式,或者我应该使用 $http 的常规方式在我继续之前使用 AngularJS' Documentation 上的方式我的项目。答案会对我有很大帮助。谢谢你。

$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('mainController',['$scope', 'foo', 'bar', function($scope, foo, bar){
    $scope.fooObj = foo;
    $scope.barObj = bar;
}])

我认为这可能是 ui-路由器解析的最佳用例。

无论如何,我更愿意将我的 http 调用包装到服务中并将此服务调用到解析中,而不是直接使用 $http。

这可能看起来像这样:

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

多亏了这一点,您可以在整个应用程序中调用此方法(并同时将其集中)。

在控制器中:

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

在解决中:

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

继续这种方法,你的方法很好。

希望对您有所帮助。

编辑:Buiplunker 添加这些方法的具体示例。