2015-11-04 108 views
23

我建一個工廠來處理功能爲我的控制器,但不知何故,在控制器上的功能之一返回一個錯誤:AngularJS錯誤.success不是一個函數

Error: Auth.getUser(...).success is not a function @http://localhost:8080/app/controllers/mainCtrl.js:10:1
...

我不知道這是怎麼回事在這裏,其餘的功能似乎工作正常?

主控制器:

angular.module('mainCtrl', []) 
.controller('mainController', function($rootScope, $location, Auth) { 
    var vm = this; 
    vm.loggedIn = Auth.isLoggedIn(); 
    $rootScope.$on('$routeChangeStart', function() { 
     vm.loggedIn = Auth.isLoggedIn(); 
     Auth.getUser() 
      .success(function(data) { 
       vm.user = data; 
      }); 
    }); 
    vm.doLogin = function() { 
     Auth.login(vm.loginData.username, vm.loginData.password) 
      .success(function(data) { 
       $location.path('/users'); 
      }); 
    }; 
}); 
+0

哪個角版本您使用的允許? –

+0

AngularJS v1.4.7,剛安裝角度與​​涼亭 –

+3

你應該使用.then()函數。你可以傳遞2個函數作爲參數,第一個用於成功回調(與.success相同),第二個用於錯誤回調。 –

回答

79

參見 '取消通知' 從$http service documentation

The $http legacy promise methods success and error have been deprecated. Use the standard then method instead.

您可以瞭解更多關於在documentation about $q這些方法。

+0

tnx在所有,你救了我的生活 –

+2

並非所有的英雄穿披肩。謝謝 –

2

你可以使用然後instate成功:

var personController = function ($scope, personService) { 
    $scope.persons = personService.getAll().then(function (data) { 
     $scope.persons = genericSuccess(data); 
    }); 
    var genericSuccess=function(res) { 
     return res.data; 
    } 
}; 
0

它是個好東西,.success已被棄用反正。我個人從來沒有與它和平,因爲你問?

object.functionCall(parameters).success(functions (response){ 

if(response!=="failure") 
do this----- 
}); 

我的意思是什麼樣的成功處理其塊內的故障。 改爲使用然後而所有邏輯將開始有意義。

0

角版本1.2.x版本,你可以使用.success 角1.6.x版,你會得到錯誤「.success是不是一個函數」

的解決方案是:將「.success」與「然後」

1

這是代碼

Depricated代碼

$http( 
{ 
    method: 'POST', 
    url: '/Home/CreateCustomer', /*You URL to post*/ 
    data: $scope.cust /*You data object/class to post*/ 
}).success(function (data, status, headers, config) 
{ 

}).error(function (data, status, headers, config) 
{ 

}); 

代碼Angular $http docs

$http(
    { 
     method: 'POST', 
     url: '/Home/CreateCustomer', /*You URL to post*/ 
     data: $scope.cust /*You data object/class to post*/ 
    }).then(function successCallback(response) { 
     // this callback will be called asynchronously 
     // when the response is available 


    }, function errorCallback(response) { 
     // called asynchronously if an error occurs 
     // or server returns response with an error status. 

});