【问题标题】:Use Ajax request using X-Auth-Token in angularjs controller [duplicate]在angularjs控制器中使用X-Auth-Token使用Ajax请求[重复]
【发布时间】:2016-12-26 18:47:55
【问题描述】:

我对使用 X-Auth-Token 的外部 API 的请求有点问题:

'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);
});
代码的结果是: enter image description here

当我尝试这样做时:

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

结果是这是一个未定义的对象。 关于这个问题的任何想法?

【问题讨论】:

  • 为什么在 Angular 应用中使用 $.ajax 而不是 $http
  • 我不知道如何将 X-Auth-Token 与 $http 一起使用!
  • 标题在文档中解释
  • angular.module('hello', ['ngRoute']) ... .controller('home', function($scope, $http) { $http.get('token') .success(function(token) { $http({ url : 'localhost:9000', method : 'GET', headers : { 'X-Auth-Token' : token.token } }).success(function(data) { $scope.greeting = data; }); }) });
  • 我在这里找到了解决方案:spring.io/blog/2015/01/20/…

标签: jquery angularjs ajax controller get


【解决方案1】:

函数$.ajax() 不返回结果,因为它是异步的。相反,您的结果是通过 success 回调提供给您的。所以你的代码应该是这样的:

'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();
});

注意:您可以使用$http.get(..) 代替$.ajax(..)。它返回一个叫做 Promise 的东西,在 Angular 应用程序中更常见。用法与上面的非常相似。是这样的:

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

您可能应该将 api 请求分离到一个服务中。如果你找到一个好的角度风格指南/最佳实践教程,你应该得到一些有价值的指导。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-20
    • 2019-05-10
    相关资源
    最近更新 更多