2014-12-23 26 views
3

我已經創建了角js中的聯繫人列表。在下面的例子中,我創建了服務工廠,因爲我無法處理服務中的$ http.post()。success()方法。

angular.module('contactApp', ['ngRoute']) 
 

 
.config(['$routeProvider', 
 
    function($routeProvider) { 
 
    $routeProvider. 
 
    when('/contactList', { 
 
     templateUrl: 'template/contactList.cfm', 
 
     controller: 'contList' 
 
    }). 
 
    when('/contactAddEdit', { 
 
     templateUrl: 'template/contactAddEdit.cfm', 
 
     controller: 'contactAddEdit' 
 
    }). 
 
    when('/contactAddEdit/:contactID', { 
 
     templateUrl: 'template/contactAddEdit.cfm', 
 
     controller: 'contactAddEdit' 
 
    }). 
 
    otherwise({ 
 
     redirectTo: '/contactList' 
 
    }); 
 
    } 
 
]) 
 

 
.controller('contList', function($scope, studentSession) { 
 

 
    studentSession.getSessions().success(function(data, status) { 
 

 
    $scope.members = = queryToObject(data); 
 

 
    }); 
 
}) 
 

 
.factory('studentSession', function($http) { 
 

 
    return { 
 

 
    getSessions: function() { 
 

 
     return $http.get('template/dbSelect.cfm'); 
 

 
    } 
 

 
    }; 
 

 
});

回答

0

您需要使用then()而不是success()您返回從廠家承諾:

studentSession.getSessions().then(function(data, status) { 

    $scope.members = = queryToObject(data); 

    }).catch(function (err) { 

    console.log(err); 
    }); 

如果需要舊瀏覽器,如IE8或Android上更多的支持手機< 4.1用此代替:

studentSession.getSessions().then(function(data, status) { 

     $scope.members = = queryToObject(data); 

     },function (err) { 

     console.log(err); 
     }); 

THEN如果你真的想返回從工廠承諾的成功,你需要一個事件:

.controller('contList', function($scope, studentSession) { 

    studentSession.getSessions(); 

    $scope.$on('session:retrievedSession', function (data) { 

    console.log('Session retrieved is: ', data.response); 
    }); 
}) 

.factory('studentSession', function($rootScope, $http) { 

    return { 

    getSessions: function() { 

     return $http.get('template/dbSelect.cfm').success(function (response) { 

     $rootScope.$broadcast('session:retrievedSession', {response:response}); 
     }); 

    } 

    }; 
}); 
+0

注意這個'.catch'將在IE8拋出一個錯誤。你可以使用'.then'的第二個參數來處理錯誤。或者如果你真的想用'catch',你必須把它寫成'[「catch」]'。 –

+0

@JonSnow;)同樣適用於Android手機<4.1 afaik :) – sbaaaang

+0

是否可以在工廠返回success()? –

相關問題