我试图调用我所做的服务中的功能。每当我尝试搜索用户名时,都会收到一条错误消息,其中显示"无法读取' getUser'未定义的。
它不应该是未定义的,我告诉它应该能够使用的用户名参数。我似乎无法找出我的服务有什么问题!
http://plnkr.co/edit/k4FD4eFuVKNvjEwKx2gs?p=preview
任何有助于推进这一进程的帮助将不胜感激:)
(function(){
var github = function($http){
var getUser = function(username){
$http.get("https://api.github.com/users/" + username)
.then(function(response){
return response.data; //still returns a promise
});
};
//angular invokes this, return an object which is github service
var getRepos = function(user){
$http.get(user.repos_url).then(function(response){
return response.data;
});
};
return {
getUser: getUser,
getRepos: getRepos
};
};
var module = angular.module("firstapp"); //get reference to existing module, NOT creating a new one
//register service with angular
module.factory("github", github);
}());
的script.js
var app = angular.module("firstapp", []) //defining module, no dependencies (so far)
.controller("MainController", ["$scope", "github", "$interval", "$log", "$anchorScroll", "$location", function(
$scope, $http, $interval, $log, $anchorScroll, $location, github) {
$scope.search = function(username) {
$log.info("Searching for "+username);
//the first parameter to .then is only invokes onusercomplete if the get is successful
//if error, it goes to second parameter which provdes error details
github.getUser(username)
.then(onUserComplete, onError);
if (countdownInterval){
$interval.cancel(countdownInterval);
$scope.countDown = null;
}
};
答案 0 :(得分:0)
问题在于依赖注入参数的顺序错误。 它是:
.controller("MainController", ["$scope", "github", "$interval", "$log", "$anchorScroll", "$location", function(
$scope, $http, $interval, $log, $anchorScroll, $location, github)
应该是:
.controller("MainController", ["$scope", "github", "$interval", "$log", "$anchorScroll", "$location","$http", function(
$scope,github,$interval, $log, $anchorScroll, $location, github,$http)
DI中的参数必须正确。
如果您遇到以下错误:
"cannot read function name of undefined"
然后你应该寻找函数调用,看看调用的对象有什么问题。
在这种情况下,github
出了问题。
答案 1 :(得分:0)
问题在于您的控制器定义中没有您的依赖项排队
.controller("MainController", ["$scope", "github", "$interval", "$log", "$anchorScroll", "$location", function(
$scope, $http, $interval, $log, $anchorScroll, $location, github) {
你的依赖关系是:
"$scope", "github", "$interval", "$log", "$anchorScroll", "$location"
但是它们会被注入
$scope, $http, $interval, $log, $anchorScroll, $location, github
你必须让订单排队,否则你会在错误的变量中有错误的依赖关系,你也不会在你列出的依赖项中添加$ http。