' TypeError:undefined不是函数'从Angular中的github api中提取json数据时?

时间:2014-08-30 04:38:00

标签: javascript json angularjs

我正在开发单页Angular应用程序并试图从github api中提取数据,该数据可以通过https://api.github.com/users/payam10访问我的github数据。

我收到错误:“TypeError:undefined不是函数”

我想做的只是取出我的登录用户名'payam10'并将其放在h1 html元素中。见下面的代码

<html ng-app="myapp">
<head>
<title>Angular</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body>
 <div ng-controller="githubController">
    <h1>{{ user.name }}</h1>
 </div>

<script>
    var myapp = angular.module('myapp', []);

    myapp.controller('githubController', ['$scope', '$http', function($scope, $http) {

        $scope.user = {}

        $scope.user.name = '';

        return $http.jsonp
                        .get('http://api.github.com/users/payam10')
                        .success(function (data, status, headers, config) {
                          // successful data retrieval
                          $scope.user.name = data.login
                        })
                        .error(function (data, status, headers, config) {
                          // successful data retrieval
                          $scope.user.name = "Sorry, we were unable to retieve your data."
                        })

    }]);

 </script>

2 个答案:

答案 0 :(得分:2)

您的代码中有错误:

$http.jsonp.get('url')...应为$http.jsonp('url')...

在你的回调中,你应该指定$scope.user = data.data来获得完整的对象。

注意data.data,因为当指定回调时,GitHub API似乎将其json包装在另一层中。

使用JSONP你还必须在你的网址中定义一个回调(我认为Angular会自动执行它,但它没有):

http://api.github.com/users/payam10?callback=JSON_CALLBACK

JSFiddle

答案 1 :(得分:0)

问题在于它是一个跨域请求。浏览器出于安全原因阻止了这种情况。

有一些解决方法。您可以查看CORS,JSONP或反向代理。