$ http.get成功;但无法访问输出?

时间:2014-05-03 10:13:25

标签: javascript json angularjs angularjs-scope promise

如何从远程服务器获取输出? - Firebug确认JSON输出正确。

这是我的尝试,我尽量做到尽可能标准(Plnkr):

app.js,controllers.js,factories.js

'use strict';

var nameVersionFactory = angular.module('name.factories.version', []);

nameVersionFactory.factory('Version', ['$q', '$http', function ($q, $http) {
    var d = $q.defer();
    $http.get('/api').then(function (response) {
        d.resolve(response);
    });

    return d.promise;
}]);

var nameVerCtrl = angular.module('name.controllers.version',
                                 ['name.factories.version']);

nameVerCtrl.controller(
    'verCtrl', ['$scope', 'Version', function ($scope, Version) {
        $scope.version = Version;  /* {'status': 'online',
                                       'rest_api_version': '1.1.14',
                                       'server_time': '…'} */
    }]
);

var nameApp = angular.module('name', ['name.controllers.version']);

/* CORS */
nameApp.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);

Python REST API(30行):https://gist.github.com/anonymous/7d34867aca543911a06f

的index.html

<!DOCTYPE html>
<html xmlns:ng="http://angularjs.org" id="ng-app" ng-app="name" lang="en">
    <head>
        <meta charset="utf-8">
    </head>

    <body>
        <div data-ng-controller="verCtrl">
            <pre>{{version | json}}</pre>
            <pre>{{version.status}}</pre>
            <pre>{{version.data | json}}</pre>
            <pre>{{version.data.status}}</pre>
        </div>

        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js">
        </script>
        <script src="scripts/controllers.js"></script>
        <script src="scripts/factories.js"></script>
        <script src="scripts/app.js"></script>
    </body>
</html>

不幸的是,我在<pre>…</pre>个标签中没有输出JSON。

1 个答案:

答案 0 :(得分:0)

Angular 1.2 +中的范围变量不再自动解包Promise。

所以,你必须这样做:

Version().then(function(result){
    $scope.version = result;    
});

此外,$http已经返回承诺,所以:

var d = $q.defer();
$http.get('/api').then(function (response) {
    d.resolve(response);
});

return d.promise;

可以简单地成为:

return $http.get("/api");