0

I've a little problem with my request to an external API which use X-Auth-Token :

'user strict';
app.controller("controller" ,function($scope,$http) {
    
    $scope.result = $.ajax({
      headers: { 'X-Auth-Token': '*****' },
      url: 'http://api.************',
      dataType: 'json',
      type: 'GET',
      success: function(data){
       return data;
       
      }
    }); 
    console.log($scope.result);
});
the result of the code is : enter image description here

When i try to do this :

console.log($scope.result.responseJSON);

The result is this one an undefined object. Any ideas about this problem ?

DJBen
  • 1
  • 1
  • why are you using `$.ajax` and not `$http` in an angular app? – charlietfl Dec 26 '16 at 19:07
  • I don't know how to use the X-Auth-Token with the $http ! – DJBen Dec 27 '16 at 19:26
  • headers are explained in the docs – charlietfl Dec 27 '16 at 21:23
  • angular.module('hello', [ 'ngRoute' ]) ... .controller('home', function($scope, $http) { $http.get('token').success(function(token) { $http({ url : 'http://localhost:9000', method : 'GET', headers : { 'X-Auth-Token' : token.token } }).success(function(data) { $scope.greeting = data; }); }) }); – DJBen Dec 31 '16 at 14:21
  • I found a solution here : https://spring.io/blog/2015/01/20/the-resource-server-angular-js-and-spring-security-part-iii – DJBen Dec 31 '16 at 14:23

1 Answers1

1

The function $.ajax() doesn't return the result, since it's asynchronous. Instead your result is given to you through the success callback. So your code should look like this:

'user strict';
app.controller("controller" ,function($scope,$http) {

    $scope.init = function(){
        $.ajax({
            headers: { 'X-Auth-Token': '*****' },
            url: 'http://api.************',
            dataType: 'json',
            type: 'GET',
            success: function(data){
                $scope.result = data;
            }
        }); 
    };

    $scope.init();
});

Note: you could use $http.get(..) instead of $.ajax(..). It returns something called a Promise and is more common in angular applications. The usage is quite similar to the above. It's something like this:

$http.get('http://api.************', {
    headers: {
       'X-Auth-Token': '*****'
    },
    responseType: 'json'
}).then(function(result){
    $scope.result = result;
});

You probably ought to separate the api requests into a service. If you find a good angular styleguide/best practices tutorial, you should get some valuable pointers.

Nikolaj Dam Larsen
  • 5,455
  • 4
  • 32
  • 45