2016-12-15 61 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适用于登录页面。

相关问题