将$ http响应对象保存为$ scope变量

Lar*_*ish 5 http angularjs

我今天早些时候在stackoverflow上问了一个相关的问题,但是由于代码的复杂性(无法发布)和我自己的新手,我无法从给出的答案中真正实现解决方案.

所以现在我的问题是,对于如下代码:

$http.get(ArbitraryInput).then(function (response) {$scope.data = response});
Run Code Online (Sandbox Code Playgroud)

(您可以用上面的"成功"代替"then",我使用"then"因为根据更新的$ http api弃用了成功)

如何在$ scope.data中实际保存响应对象?从我到目前为止所做的,$scope.data当我后来输入代码时是"未定义的":

console.log($scope.data3);
Run Code Online (Sandbox Code Playgroud)

谢谢!

更新一个

显然,如果我把console.log($scope.data); 里面的控制台将显示我想要的$scope.data.但如果它在外面,它将在控制台中保持"未定义".换一种说法:

$http.get(ArbitraryInput).then(function (response) {$scope.data = response; console.log($scope.data);});
Run Code Online (Sandbox Code Playgroud)

将返回任何类型的对象响应.在控制台中,但是

$http.get(ArbitraryInput).then(function (response) {$scope.data = response;});
console.log($scope.data);
Run Code Online (Sandbox Code Playgroud)

将在控制台中返回"undefined".

Wil*_*m B 6

您需要利用$ 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 */);
    };
}) ;
Run Code Online (Sandbox Code Playgroud)


小智 5

问题已得到解答,但是如果需要立即提供数据,则希望提供备用解决方案.您可以将该数据解析为路由中的依赖项,而不是直接在控制器/指令中调用$ http服务,因此可以立即获得数据:

angular.module('myApp')
    .config(['$routeProvider', function($routeProvider) {
        $routeProvider.when('/home', {
            templateUrl: '/path/to/template',
            controller: 'myCtrl',
            controllerAs: 'ctrl',
            resolve: {
                myData: ['$http', function($http) {
                    return $http.get('/end/point');
                }
            }
        }
    }]);
Run Code Online (Sandbox Code Playgroud)

然后您的控制器可能如下所示:

angular.module('myApp')
    .controller('myCtrl', ['myData', function(myData) {
        var self = this;
        self.data = myData;
    }]);
Run Code Online (Sandbox Code Playgroud)

在你看来:

<pre>{{ctrl.data|json:4}}</pre>
Run Code Online (Sandbox Code Playgroud)

将所有数据显示为JSON,而无需在控制器中调用$ http.