为什么$ http.get()在我的角度服务未定义? [英] Why is $http.get() undefined in my Angular service?
问题描述
我试图加载一些JSON,并将其存储使用$ rootScope使其控制器之间仍然存在。当我运行我的应用程序,我得到了以下错误:
类型错误:不能调用方法'得到'的未定义
get方法是完美的工作,直到我试图引进$ rootScope ...任何想法?
我的服务是这样的:
1 / **
2 *服务从JSON源获取测验数据
3 * /
4 app.factory('quizService',['$ rootScope',函数($范围,$ rootScope,$ HTTP){
5 VAR的承诺;
6 VAR的服务= {
7 getQuiz:功能($范围,$ HTTP){
8,如果(!诺){
9承诺= $ http.get('QuizFileName.quiz'),然后(功能(响应){
10回response.data;
11});
12}
13回报的承诺;
14}
15};
16退换货服务;
17}]);
我的控制器看起来是这样的:
7 //从服务测验数据
8 quizService.getQuiz()。然后(功能(数据){
9 $ scope.quiz =数据;
10
11 //重定向到的分数,如果已经完成此
12如果($ scope.quiz.complete ===真){
13 $ location.path('分数');
14}
15});
OK,Reboog711把我在正确的轨道上,我需要修改我厂定义,包括$ HTTP,我不得不previously试图做到这一点,却误把它在一起是这样的:
'$ rootScope,$ HTTP
不这样做,这是坏的,错了!但Reboog711的回答也给了我的错误,因为我认为你不能在路上使用$范围内,我们都认为。
正确(或工作)的解决方案是:
app.factory('quizService',['$ rootScope,$ HTTP',函数($ rootScope,$ HTTP){
我希望这可以帮助其他的新人角。非常感谢所有谁与他们的意见回答。我真的很尊重这个社会对伟大的态度来帮助他人:)
I'm trying to load some JSON and store it using $rootScope so that it persists between controllers. When I run my app I get the following error:
TypeError: Cannot call method 'get' of undefined
The get method was working perfectly until I tried to introduce $rootScope... any ideas?
My service looks like this:
1 /**
2 * Service to get the quiz data from a JSON source
3 */
4 app.factory('quizService', ['$rootScope', function ($scope, $rootScope, $http) {
5 var promise;
6 var service = {
7 getQuiz: function($scope, $http) {
8 if ( !promise ) {
9 promise = $http.get('QuizFileName.quiz').then(function (response) {
10 return response.data;
11 });
12 }
13 return promise;
14 }
15 };
16 return service;
17 }]);
My controller looks like this:
7 // Get Quiz data from service
8 quizService.getQuiz().then(function(data) {
9 $scope.quiz = data;
10
11 // Redirect to scores if already completed this
12 if($scope.quiz.complete === true) {
13 $location.path('scores');
14 }
15 });
OK, Reboog711 put me on the right track, I needed to modify my factory definition to include $http, I had previously tried to do this, but mistakenly put it together like this:
'$rootScope, $http'
Don't do this, it's bad and wrong! But Reboog711's answer also gave me errors because I think you can't use $scope in the way we both thought.
The correct (or working) solution was:
app.factory('quizService', ['$rootScope', '$http', function ($rootScope, $http) {
I hope this helps other newcomers to Angular. Many thanks to all who replied with their comments. I really respect this community for its great attitude to helping others :)
这篇关于为什么$ http.get()在我的角度服务未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!