ui路由器解决链接承诺

时间:2014-07-24 16:39:01

标签: angularjs angular-ui-router resolve angular-promise

使用ui-router更改状态时需要一些数据 这些数据相互依赖,所以我必须使用链接承诺

svc.getData1AndData2 = function(){
        var defer = $q.defer();
        $q.all([svc.getDatas1(),svc.getDatas2()]).then(function(values) {
            $rootScope.datas2 = values[1];
            $rootScope.datas1 = values[0];
            defer.resolve(values);
        }, function(error) {
            console.log(error);
            defer.reject(error);
        });
    return defer.promise;

svc.getData3Sources = function(){
        svc.getData1AndData2().then(function(value){
            return svc.getSources(24);
        })
    };

svc.getSources=function(id){
        var defer = $q.defer();
        Services.query({Id:id}, function(data){
                defer.resolve(data);
            };
    };

我的状态是

.state('secure.list', {
       url: "/list",
       templateUrl: "views/list.html",
       controller: 'ListCtrl',
       resolve: {
              InitData: function (InitFactory) {
              return InitFactory.getData3Sources();
              }
        }
})

它返回undefined。谁知道为什么?

1 个答案:

答案 0 :(得分:0)

svc.getData3Sources不会返回任何内容..

试试......

svc.getData1AndData2 = function(){
    // no need to use $defer here

    var promise = $q.all([svc.getDatas1(),svc.getDatas2()]).then(function(values) {
        $rootScope.datas2 = values[1];
        $rootScope.datas1 = values[0];

        return values;
    }, function(error) {
        console.log(error);
        defer.reject(error);
    });

    return promise;
}; // this line was missing

svc.getData3Sources = function(){
    var promise = svc.getData1AndData2().then(function(values){ 
        // changed value to values in the line above 
        // as the promise in getData1AndData2 resolves  ... valueS

        // why don't you use the values from getData1AndData2 ?? 
        return svc.getSources(24);
    });

    return promise;
};

svc.getSources=function(id){
    var defer = $q.defer();

    // it looks like you're having to use $q.defer 
    // as your Service.Query takes a callback rather than returning a promise
    // if you control this then a promise would be much better
    Services.query({Id:id}, function(data){
            defer.resolve(data);
        }); // the bracket ')' here was missing

    return defer.promise; // this line was missing
};