$ http.get(...)。成功不是一个功能

时间:2016-12-15 16:51:55

标签: javascript angularjs ajax function

我有这段代码:

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

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

  

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

有什么想法吗?感谢

3 个答案:

答案 0 :(得分:184)

unsigned int语法在Angular v1.4.3之前是正确的。

对于Angular v.1.6之前的版本,您必须使用.success方法。 then方法有两个参数:一个then()和一个success回调,它将使用响应对象调用。

使用error方法,将then()函数附加到返回的callback

这样的事情:

promise

参见参考here.

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 是传输数据的绝佳方式,在 AngularJS

中很容易使用

2之间的主要区别在于JSON调用返回.then()(使用promise返回的值解析),而callback是更传统的注册方式.success()并且不会返回callbacks

答案 1 :(得分:6)

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

答案 2 :(得分:2)

如果您在2017年10月21日之前尝试使用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");
        });

上述片段适用于登录页面。

相关问题