$http.get(...).success 不是函数

新手上路,请多包涵

我有这个代码:

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

在我的本地环境中,工作正常,但在服务器中,返回此错误:

TypeError: $http.get(…).success 不是函数

有任何想法吗?谢谢

原文由 Alejo Ribes 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 381
2 个回答

.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 (response){

   },function (error){

   });
}

请参阅 此处的参考。

Shortcut 方法也可用。

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

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

您从响应中获得的数据预计采用 JSON 格式。 JSON 是一种很好的 数据 传输方式,并且在 AngularJS 中使用起来很容易

The major difference between the 2 is that .then() call returns a promise (resolved with a value returned from a callback ) while .success() is更传统的注册方式 callbacks 并且不返回 promise

原文由 Mihai Alexandru-Ionut 发布,翻译遵循 CC BY-SA 3.0 许可协议

这可能是多余的,但上面投票最多的答案说 .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.');
});

原文由 Ian Poston Framer 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题