javascript - AngularJS $http 返回值

标签 javascript ajax angularjs

我是 AngularJS 的新手,只了解 AngularJS 的基础知识。我想从 $http 返回一个值。即$http应该返回一个值给My Application的全局变量。

我试过这个:

var sessionValues = null;
var AdminController = angular.module('AdminController', []);

AdminController.controller('LoginController', ['$scope', '$http','$location',
function ($scope, $http, $location){
$http({
        method: "post",
        url: "API/MyPage.php",
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).success(function(data){
        sessionValues = eval(data);
        console.log(sessionValues); /*Returns desired string*/
    }).error(function(){
        $scope.message="Some error has occured";
    });
    console.log(sessionValues); /*Returns null */
  }
]);

我尝试使用 $rootScope,但没有成功。

我理解这是因为是异步调用,但是如何获取JS全局变量中的值呢?

谁能帮我解决这个问题?

最佳答案

问题确实在于调用的异步性质以及您尝试访问变量的时间。 console.log 返回 null,因为它在 $http 调用完成之前被调用。

首先我们不污染JavaScript全局作用域,而是使用services\factory, $rootScope来访问数据。

在这种情况下,如果您想跨 Angular 公开变量,最简单的方法是使用 $rootScope。像这样

AdminController.controller('LoginController', ['$scope','$http','$location','$rootScope'
  function ($scope, $http, $location,$rootScope){
  $http({
        method: "post",
        url: "API/MyPage.php",
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).success(function(data){
        $rootScope.sessionValues = eval(data);
        console.log($rootScope.sessionValues); /*Returns desired string*/
    }).error(function(){
        $scope.message="Some error has occured";
    });
    console.log($rootScope.sessionValues); /*Returns will always null due to async nature call*/
  }
]);

然后您必须仅在成功回调中填充该变量后才能访问该变量,在此之前它始终为空。 console.log 总是失败。

要知道变量值何时更改,您可以使用 AngularJS watch http://www.benlesh.com/2013/08/angularjs-watch-digest-and-apply-oh-my.html

关于javascript - AngularJS $http 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24595917/

相关文章:

javascript - Angular UI 多个弹出窗口,提交后以编程方式关闭单个弹出窗口

javascript - Material-UI DropZone "getFileAddedMessage"处理程序在单个字符串中返回多个文件名

php - 从客户端向服务器发送变量 | JSON 与 POST

javascript - ajax调用中的安全问题

javascript - Angularjs input[placeholder] 指令与 ng-model 中断

angularjs - 如何在angularjs中显示mysql图像? (AngularJs -> Node.js -> abc.com -> mysql)

javascript - 我如何检测函数何时作为 jQuery 回调调用与直接调用?

javascript - 将 HTML 中的用户输入值传递给 jQuery.Ajax

javascript - Angularjs 1.6组件: TypeError: Cannot set property 'detailsView' of undefined

javascript - 如何使用 Vue-Router 在 Vue 中设置数组 URL 查询参数