AngularJS Defer.promise工作不正常(AngularJS Defer.promi

2019-10-19 09:33发布

我正在开发使用AngularJSPersistenceJS的应用程序。

我得到处理异步调用麻烦的

控制器

cars.controller('CrashWidgetOneCtrl',function($scope, $location, $routeParams, CrashServices){  
    if($routeParams.crashId){
        $scope.data = {};
        console.log("CrashID: "+$routeParams.crashId);
        crashId = $routeParams.crashId; 
        alert(1);//Works

        CrashServices.getCrashDetails($scope, crashId).then(function(result){
            console.log(result);
            alert(2);//Never Fires
        });    
    alert(3);//Gets executed
    }else{
        console.log("N");
    }   

});

服务项目

cars.factory('CrashServices', function($http, $location, $q, CommonServices,$rootScope, $timeout){
    return{
        getCrashDetails:function($scope, crashId){
        var deferred = $q.defer();          
        // Get user details if any
        $scope.$apply(function(){
            var crashInfoTable = App.CrashInfoTable.all();
            alert(4);
            crashInfoTable.list(null, function (results) { 
                alert(5);//This also doesn't work
                deferred.resolve();
            }); 
        });
        return deferred.promise;
        }
    }

});

任何帮助将不胜感激。 非常感谢。

注:我使用PersistenceJS。

Answer 1:

我不知道你是否需要scope.apply。 这似乎为我工作:

getCrashDetails:function($scope, crashId){
    var deferred = $q.defer();          
    // Get user details if any
    App.CrashInfoTable.all().list(null, function(results) { 
        deferred.resolve(results);
    });
    return deferred.promise;
}


文章来源: AngularJS Defer.promise not working as expected