1

使用 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();
              }
        }
})

它返回未定义。谁知道为什么?

4

1 回答 1

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
};
于 2014-07-24T17:15:41.680 回答