AngularJS Defer.promise not working as expected

妖精的绣舞 提交于 2020-01-05 12:11:43

问题


I'm developing an application using AngularJS & PersistenceJS.

I'm getting trouble dealing with Asynchronous calls as the

Controller :

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");
    }   

});

Services :

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;
        }
    }

});

Any help will be greatly appreciated. Many thanks.

Note: I am using PersistenceJS.


回答1:


I dont know if you need the scope.apply. This seemed to work for me:

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;
}


来源:https://stackoverflow.com/questions/21986659/angularjs-defer-promise-not-working-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!