1

In angular js version 1.2.9 "success" function works but in 1.6 it uses "then" function which works so how can I convert the following code using then

artistControllers.controller('DetailsController', ['$scope', '$http','$routeParams', function($scope, $http, $routeParams) {
  $http.get('js/data.json').success(function(data) {
    $scope.artists = data;
    $scope.whichItem = $routeParams.itemId;
  });
}]);

5 Answers 5

3

.success is deprecated for versions above 1.3. You should use .then

artistControllers.controller('DetailsController', ['$scope', '$http','$routeParams', function($scope, $http, $routeParams) {
  $http.get('js/data.json').then(function(data) {
    $scope.artists = data;
    $scope.whichItem = $routeParams.itemId;
  });
}]);
Sign up to request clarification or add additional context in comments.

Comments

1

The .success syntax was correct up to Angular v1.4.3.

For versions up to Angular v.1.6, you have to use then method. The then() method takes two arguments: a success and an error callback which will be called with a response object.

Using the then() method, attach a callback function to the returned promise.

Something like this:

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

   },function (error){

   });
}

See reference here.

Shortcut methods are also available.

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

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

The major difference between the 2 is that .then() call returns a promise (resolved with a value returned from a callback) while .success() is more traditional way of registering callbacks and doesn't return a promise.

Solution

artistControllers.controller('DetailsController', ['$scope', 
  '$http','$routeParams', function($scope, $http, $routeParams) {
    $http.get('js/data.json').then(function(data) {
      $scope.artists = data;
      $scope.whichItem = $routeParams.itemId;
    });
}]);

Comments

0

try this....

$http.get("http://localhost/angulartest/index.php/Items/getItems")
    .then(function (response) {

        console.log(response.data);
        $scope.records = response.data;
    });

Comments

0

The structure of $http has changed. Use .then instead of .success

$http.get('js/data.json').then(function(data){
   console.log(data);
}).catch(function(error)){
console.log(error)
});

Comments

0

Do three things

  1. Replace success() with then()
  2. Replace error() with catch()
  3. Consider response.data not the response

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.