hakuna
hakuna

Reputation: 6701

AngularJS - ReferenceError: success is not defined

I am getting "ReferenceError: success is not defined" when doing a Restful call from controller to my node.js back end as follows:

authControllers.js:

authControllers.controller('authCtrl', ['$scope', '$location', '$window', 'UserService', 'AuthenticationService',
function authCtrl($scope, $location, $window, UserService, AuthenticationService) {
  $scope.me = function() {    
    UserService.me(function(res) {
      $scope.myDetails = res;
    }, function() {
      console.log('Failed to fetch details');
      $rootScope.error = 'Failed to fetch details';
    })
  };      
}]);

authServices.js:

authServices.factory('UserService',['$http', function($http) {
  return {        
    me:function() {
    return $http.get(options.api.base_url + '/me').success(success).error(error)
    }
  }
}]);

html:

<div class="row" data-ng-controller="authCtrl" data-ng-init="me()">
    <div class="col-lg-12">
        <div class="panel panel-primary">
            <div class="panel-heading">
                <strong>Your Details</strong>
            </div>
            <div class="panel-body">
                <p>{{myDetails.data.username}}</p>
                <p>{{myDetails.data.email}}</p>
            </div>
        </div>
    </div>
</div>

A successful nodeJs call is being received and it's returning data as well, but couldn't get it in the front end. Please help !

Upvotes: 3

Views: 4513

Answers (2)

V31
V31

Reputation: 7666

.success and .error are not part of the $http.get call. $http.get itself is a promise so when calling your service you need to have

authControllers.controller('authCtrl', ['$scope', '$location', '$window', 'UserService', 'AuthenticationService',
function authCtrl($scope, $location, $window, UserService, AuthenticationService) {
  $scope.me = function() {    
    UserService.me().then(function(res) {
      $scope.myDetails = res;
    }, function() {
      console.log('Failed to fetch details');
      $rootScope.error = 'Failed to fetch details';
    })
  };      
}]);

and your service is to be kept simple:

authServices.factory('UserService',['$http', function($http) {
  return {        
    me:function() {
    return $http.get(options.api.base_url + '/me');
    }
  }
}]);

More on $http

Upvotes: 2

AJcodez
AJcodez

Reputation: 34156

The error is:

return $http.get(options.api.base_url + '/me').success(success).error(error)

To fix it, don't try to reference success and error functions that don't exist.

return $http.get(options.api.base_url + '/me')

Angular returns a $q promise when you call $http, which you use correctly. The success and error resolution methods are deprecated.

The $http legacy promise methods success and error have been deprecated.

Upvotes: 5

Related Questions