Angular-UI路由器 - 决定不等待承诺解决?

iQ.*_*iQ. 4 angularjs angular-ui-router

总结一下,我使用angular-ui路由器解析函数来检索状态特定数据.但是它似乎没有完全等待解决的承诺:

state('parent.ChildState', {
                url: '/myUrl?param1&param1',
                templateUrl: 'views/list.view.html',
                controller: 'MyController',
                resolve: {
                    data: resolveData
                }
            }).

    function resolveData($stateParams, Utils) {
        var filters = Utils.getFilters($stateParams);

        DataService.myDataObj = DataService.get(filters, function(result, headers) {
            DataService.myDataObj = result;
        });
        return DataService.myDataObj;

        // Note I have also tried returning directly the DataService.get call however this makes all the below console log statements as undefined (see below for the controller code to know what I mean). So I do the assignment first and then return that.
    }
Run Code Online (Sandbox Code Playgroud)

现在在控制器中我有一个在加载时执行的函数,如下所示:

    function ExpensesController(DataService) {

        $scope.viewData = DataService;

        initData();

        function initData() {
            // this generally logs a ngResource and shows the full data obj on console
            console.log($scope.viewData.myDataObj);

           // this gets undefined on console
           console.log($scope.viewData.myDataObj.someField1); 

           // this log fine, however why do I need to do promise      
           // resolve? should be resolved already right?
           $scope.viewData.myDataObj.$promise.then(function() {
               console.log($scope.viewData.myDataObj.someField1);
           });
Run Code Online (Sandbox Code Playgroud)

lev*_*evi 5

由于要解决的所需数据是异步的,因此需要return在回调函数中返回promise和add 语句.

function resolveData($stateParams, Utils) {
    var filters = Utils.getFilters($stateParams);

    return DataService.get(filters, function(result, headers) {
         DataService.myDataObj = result;
         return DataService.myDataObj
    });
}
Run Code Online (Sandbox Code Playgroud)

您可以阅读ui-router解决文档更多关于解析器如何工作以及何时应返回promise或纯值的文档.