Error with $http.get in angularJS -- Success not a Function [duplicate]
Asked Answered
D

9

28

Getting this error:

angular.min.js:122 TypeError: $http.get(...).success is not a function at getUserInfo (app.js:7) at new (app.js:12) at Object.invoke (angular.min.js:43) at Q.instance (angular.min.js:93) at p (angular.min.js:68) at g (angular.min.js:60) at g (angular.min.js:61) at g (angular.min.js:61) at angular.min.js:60 at angular.min.js:21

Here is my code:

var gitHub = angular.module('gitHub', []);

gitHub.controller('mainController', ['$scope', '$http', function($scope, $http) {

    var $scope.user = '';
    function getUserInfo($scope, $http){ 
        $http.get('https://api.github.com/users')
            .success(function (result) {
                $scope.user = result;
                console.log(result);
            });
    };
    getUserInfo($scope, $http);
}]);

and here is the html

<!DOCTYPE html>
<html ng-app="gitHub">
<head>
    <title>Github Users Directory</title>
    <script src="angular.min.js"></script>
    <script src="app.js"></script>
</head>
<body>
    <div ng-controller="mainController">
        <div>
            <h1>GitHub Users</h1>
            Who do you want to search for?<input type="text" name="FindHim" ng-model="queryName" />
            <button ng-click="getUserInfo()">Search</button>
        </div>
        <div>
            {{ user }}
        </div>

    </div>
</body>
</html>
Dalmatic answered 16/12, 2016 at 11:55 Comment(3)
Which version of angular?Frightened
The success and error callbacks are deprecated since (I think) angular 1.5Frightened
The .success and .error methods are deprecated and have been removed from AngularJS 1.6.Ona
O
61

The .success and .error methods are deprecated and have been removed from AngularJS 1.6. Use the standard .then method instead.

$http.get('https://api.github.com/users')
  .then(function (response) {

    var data = response.data;
    var status = response.status;
    var statusText = response.statusText;
    var headers = response.headers;
    var config = response.config;

    $scope.user = data;
    console.log(data);
});

Deprecation Notice

The $http legacy promise methods .success and .error have been deprecated and will be removed in v1.6.0. Use the standard .then method instead.

— AngularJS (v1.5) $http Service API Reference -- Deprecation Notice.

Also see SO: Why are angular $http success/error methods deprecated?.

Ona answered 16/12, 2016 at 15:18 Comment(0)
S
15

i think you need to use .then and not .success when using angular.

Example from the doc's

var promise = asyncGreet('Robin Hood');
promise.then(function(greeting) {
  alert('Success: ' + greeting);
}, function(reason) {
  alert('Failed: ' + reason);
}, function(update) {
  alert('Got notification: ' + update);
});

Here is the example of how $Http uses it:

// Simple GET request example:
$http({
  method: 'GET',
  url: '/someUrl'
}).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.
  });

And finally your code could look like this

$scope.getUserInfo = function () {
    $http.get('https://api.github.com/users')
        .then(function (result) {
            $scope.user = result;
            console.log(result);
        }, function(result) {
            //some error
            console.log(result);
        });
};
Serration answered 16/12, 2016 at 11:58 Comment(1)
They don't need to use .then() although they should as .success() is deprecated. You should probably give an example though that uses $http with .then() rather than a generic promise example.Salmagundi
B
4

this works

https://docs.angularjs.org/api/ng/service/$http

// Simple GET request example:
$http({
  method: 'GET',
  url: '/someUrl'
}).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.
  });
Bolger answered 14/2, 2017 at 19:35 Comment(0)
P
2

As per your current implementation, You are not passing arguments (i.e. $scope and $http) to getUserInfo from ng-click="getUserInfo()" thus you are getting the error.

You don't need to pass these as arguments as $scope and $http as its already injected in controller and define the function in $scope.

gitHub.controller('mainController', ['$scope', '$http', function($scope, $http) {

    $scope.user = '';
    //Redefined function, without arguments
    $scope.getUserInfo = function (){ 
        $http.get('https://api.github.com/users')
            .success(function (result) {
                $scope.user = result;
                console.log(result);
            });
    };
    $scope.getUserInfo();
}]);
Pear answered 16/12, 2016 at 11:59 Comment(5)
Dont, same error, although I'm able to do it with using .then instead of .success methodDalmatic
Borrowed your code to give him an example using .thenSerration
@devzero, Never mindPear
@ManzurKhanSarguroh, Which version of angular you are using?Pear
@Pear version 1.6Dalmatic
E
1

You dont need to inject $scope, $http..

app.controller('MainController', function($scope, $http) { 
  $scope.fetchData = function(_city){
    $http.get("../api/AllPlaces?filter[where][placeCity]="+ _city)
    .then(function(response) {
      $scope.Data = response.data;
    });
  }
});
Effervescent answered 20/7, 2017 at 11:24 Comment(0)
C
0

No need to pass $http as a function parameter, since you have already injected $http as a dependency to your controller. I have made some modification to the code. Please check it will work fine for you.

var gitHub = angular.module('gitHub', []);

gitHub.controller('mainController', ['$scope', '$http', function ($scope, $http) {

    $scope.user = '';

    $scope.getUserInfo = function() {
        $http.get('https://api.github.com/users')
            .success(function (result) {
                $scope.user = result;
                console.log(result);
            });
    };
    $scope.getUserInfo();
}]);
Conduct answered 16/12, 2016 at 12:11 Comment(0)
T
0
$http({
    method: 'GET',
    url: '....',
    headers: {
        'Authorization': 'Bearer ' + localStorage["token"]
    }
})
.then(function (data, status, headers, config) {
     alert(JSON.stringify(data) + "Status" + status);
})
.error(function (data, status, headers, config) {
     alert(JSON.stringify(data) + "Status" + status);
});
Tensor answered 7/7, 2017 at 11:21 Comment(2)
please format your code properlyFrodeen
The .error method is deprecated. Instead use .catch.Ona
E
0

According to Angular JS $http documentation, this system has been excludede from 1.4.3 + So, I have taken help from his post and you can try this way

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

   },function (error){

   });
}

OR

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

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

I prefer the second one which was more flexible for me.

Erna answered 24/11, 2017 at 7:4 Comment(0)
B
-1
function successCallback(response) {
return response
}
$http.get('url')
.then(successCallback)
Bravado answered 31/7, 2017 at 10:50 Comment(1)
Thank you for this code snippet, which may provide some immediate help. A proper explanation would greatly improve its educational value by showing why this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply.Aeroembolism

© 2022 - 2024 — McMap. All rights reserved.