我今天早些时候在stackoverflow上问了一个相关的问题,但是由于代码的复杂性(无法发布)和我自己的新手,我无法从给出的答案中真正实现解决方案.
所以现在我的问题是,对于如下代码:
$http.get(ArbitraryInput).then(function (response) {$scope.data = response});
(您可以用上面的“成功”代替“then”,我使用“then”因为根据更新的$http api弃用了成功)
如何在$scope.data中实际保存响应对象?从我到目前为止所做的,当我后来输入代码时,$scope.data是“未定义的”:
console.log($scope.data3);
谢谢!
更新一个
显然,如果我把console.log($scope.data);在控制台内部将显示我想要的$scope.data.但如果它在外面,它将在控制台中保持“未定义”.换一种说法:
$http.get(ArbitraryInput).then(function (response) {$scope.data = response; console.log($scope.data);});
将返回任何类型的对象响应.在控制台中,但是
$http.get(ArbitraryInput).then(function (response) {$scope.data = response;}); console.log($scope.data);
将在控制台中返回“undefined”.
解决方法
您需要利用$http.get返回一个promise的事实,并在任何需要访问已解析数据的代码中链接到该promise:
app.controller('Ctrl',function($scope,mainInfo){ var request = $http.get(ArbitraryInput).then(function (response) { $scope.data = response; return response; // this will be `data` in the next chained .then() functions }); request.then(function (data) {/* access data or $scope.data in here */}); $scope.someFunction = function () { request.then(function (data) {/* access data or $scope.data in here */); }; }) ;