2016-12-15 63 views
60

我有這樣的代碼:

app.controller('MainCtrl', function ($scope, $http){ 
    $http.get('api/url-api') 
    .success(function (data, status, headers, config){ 
    } 
} 

在我的本地環境,工程確定,但在一臺服務器,這個錯誤:

TypeError: $http.get(...).success is not a function

任何想法?謝謝

+1

本地envm和服務器上的版本是什麼?順便說一句,[_ $ http.get_](https://docs.angularjs.org/api/ng/service/$http#get)返回HttpPromise,所以你需要使用_then_而不是 – Grundy

+0

你有沒有檢查過你所有的JavaScript加載服務器環境? – bansi

+6

其''然後()'不'成功()' –

回答

123

.success語法是正確的,直到Angular v1.4.3。

對於高達Angular v.1.6的版本,您必須使用then方法。 then()方法有兩個參數:一個success和一個error回調,它將用響應對象調用。

使用then()方法,將callback函數附加到返回的promise

事情是這樣的:

app.controller('MainCtrl', function ($scope, $http){ 
    $http({ 
     method: 'GET', 
     url: 'api/url-api' 
    }).then(function (success){ 

    },function (error){ 

    }); 
} 

見參考文獻here.

Shortcut方法也可用。

$http.get('api/url-api').then(successCallback, errorCallback); 

function successCallback(response){ 
    //success code 
} 
function errorCallback(error){ 
    //error code 
} 

您從響應中獲得的數據預計爲JSON格式。 JSON是運輸數據的好方法,而且很容易內AngularJS使用

2之間的主要區別是,.then()調用返回從callback返回promise(用值來解析)而.success()是更傳統的註冊方式callbacks,並且不返回promise

+0

我嘗試使用.then並且正常工作,感謝Alexandru -Ionut Mihai –

+1

'.success'和'.then'採取不同的參數,佔到 –

1

這可能是多餘的,但上面投票最多的答案是.then(function (success),對於我而言這並不適用於Angular版本1.5.8。取而代之的是使用response然後在塊response.data裏面找到了我正在尋找的json數據。

$http({ 
    method: 'get', 
    url: 'data/data.json' 
}).then(function (response) { 
    console.log(response, 'res'); 
    data = response.data; 
},function (error){ 
    console.log(error, 'can not get data.'); 
}); 
+0

我的意思是...你試過'success.data'嗎?在這種情況下參數名稱並不重要。 –

+0

我的代碼有效。當我按照上面的答案時,我被卡住了。這也是一種實際獲取數據並將其記錄到控制檯的方法。這可以向開發人員展示如何在瀏覽器中測試他們的數據。我在這裏被問題標題中的同樣的確切錯誤帶到這裏。 –

+0

舊的代碼'$ http.get('data/data.json')。success(function(data){data = data;}'開發人員現在知道它的'data.data'不能獲取數據因此我的回答對於這個錯誤信息很重要 –

0

如果您在21/10/2017時試圖使用AngularJs 1.6.6,那麼以下參數將作爲.success運行並且已經耗盡。 .then()方法有兩個參數:一個響應和一個錯誤回調,它將用響應對象調用。

$scope.login = function() { 
     $scope.btntext = "Please wait...!"; 
     $http({ 
      method: "POST", 
      url: '/Home/userlogin', // link UserLogin with HomeController 
      data: $scope.user 
     }).then(function (response) { 
      console.log("Result value is : " + parseInt(response)); 
      data = response.data; 
      $scope.btntext = 'Login'; 
      if (data == 1) { 
       window.location.href = '/Home/dashboard'; 
      } 
      else { 
      alert(data); 
     } 
     }, function (error) { 

     alert("Failed Login"); 
     }); 

上面的snipit適用於登錄頁面。

相關問題