我的angularjs-application存在问题。我一直在网上做一些研究,但我不明白如何解决这个问题。在角度方面,我完全是诺贝尔。
我尝试构建一个应用程序,通过API解析来自GitHub的信息,以在我的表中显示用户信息。但是,经过一些处理将代码拆分成多个js文件后,它带来了问题。
提前谢谢
NG-应用
(function(){
var app = angular.module("app", ["ngRoute"]);
app.config(function($routeProvider){
$routeProvider
.when("/index.html", {
templateUrl: "index.html",
controller: "searchForData"
})
.when("/github/:username", {
templateUrl: "/templates/github.html",
controller: "githubController"
})
.when("/tv", {
templateUrl: "/templates/tv.html",
controller: "searchForData"
})
.otherwise({redirectTo:"/index"});
});
}());
纳克控制器
(function() {
var app = angular.module('app');
var githubController = function($scope, github, $routeParams){
var onGithubComplete = function(data){
$scope.user = data;
github.getRepos($scope.user).then(onGitHubRepos, onError);
};
var onGitHubRepos = function(data){
$scope.repos = data;
};
var onError = function(reason) {
$scope.error = "Could not fetch data";
};
$scope.username = $routeParams.username;
github.getUser($scope.username).then(onGithubComplete, onError);
};
app.controller("githubController", githubController);
}());
githubService.js
(function() {
var github = function($http){
var getUser = function(username){
return $http.get("https://api.github.com/users/" + username).then(function(response){
return response.data;
});
};
var getRepos = function(user){
$http.get(user.repos_url).then(function(response){
return response.data;
});
};
return {
getUser: getUser,
getRepos: getRepos
};
};
var module = angular.module("app");
module.factory("github", github);
}());
search.js
(function() {
var app = angular.module('app');
var searchForData = function($scope, $http, $location){
var onError = function(reason) {
$scope.error = "Could not fetch data";
};
$scope.search = function(searchWord){
$scope.array = searchWord.split(':');
switch($scope.array[0]) {
case 'github':
$location.path("/github/" + $scope.array[1]);
break;
default:
break;
}
};
};
app.controller("searchForData", searchForData);
}());
错误
TypeError:无法读取未定义的属性'then' 在onGithubComplete(githubController.js:8) 在C(angular.js:10725) 在angular.js:10811 at h。$ eval(angular.js:11726) at h。$ digest(angular.js:11554) at h。$ apply(angular.js:11832) 在f(angular.js:7774) 在K(angular.js:7947) 在XMLHttpRequest.y.onreadystatechange(angular.js:7903)
答案 0 :(得分:1)
您缺少return
声明。
注意区别:
var getUser = function(username) {
return $http.get("https://api.github.com/users/" + username).then(function(response) {
return response.data;
});
};
var getRepos = function(user) {
$http.get(user.repos_url).then(function(response) {
return response.data;
});
};
答案 1 :(得分:0)
修改你的githubService -
var getRepos = function(user){
$http.get(user.repos_url).then(function(response){
return response.data;
});
};
到
var getRepos = function(user){
return $http.get(user.repos_url);
};
然后在您的控制器中执行then
-
var onGithubComplete = function(data){
$scope.user = data;
github.getRepos($scope.user).then(onGitHubRepos, onError);
};