Reputation: 867
I just started out coding angular, and I'm not sure what I'm exactly doing wrong.
I have a factory with a method that uses an $http get:
angular.module('d3_survey')
.factory('currentSurvey', ['$http', function($http) {
return{
sweep : function(number) {
console.log('resources/currentSurvey/' + number + '.json');
return $http.get('resources/currentSurvey/' + number + '.json').then(function (response) {
return response;
});
}
}
}]);
I thought that I could do this since sweep is a closure and everything and it would still have access to $http. I resolve the service in my ui-router config.
resolve : {
surveyDetails : ['surveyQuestions', function(surveyQuestions){
return surveyQuestions.all();
}],
messages : ['currentSurvey', function(currentSurvey) {
return currentSurvey;
}]
}
I inject "messages" onto my controller and try to call the sweep method:
var messages = $scope.currentSurvey.sweep('1');
$scope.result = JSON.stringify(messages);
But when I bind $scope.result to my view I get something weird on the page:
{"$$state":{"status":0}}
I saw other questions where some people have done a further .then() on the result of the factory method, but even this didn't work out.
This is what I see on the console, but it doesn't make any sense:
SyntaxError: Unexpected token m
at Object.parse (native)
at pc (http://localhost:63342/SurveyTool/js/angular.min.js:14:208)
at Zb (http://localhost:63342/SurveyTool/js/angular.min.js:76:379)
at http://localhost:63342/SurveyTool/js/angular.min.js:77:237
at s (http://localhost:63342/SurveyTool/js/angular.min.js:7:302)
at Zc (http://localhost:63342/SurveyTool/js/angular.min.js:77:219)
at c (http://localhost:63342/SurveyTool/js/angular.min.js:78:349)
at http://localhost:63342/SurveyTool/js/angular.min.js:112:20
at l.$eval (http://localhost:63342/SurveyTool/js/angular.min.js:125:305)
at l.$digest (http://localhost:63342/SurveyTool/js/angular.min.js:122:398) angular.js:11939
Upvotes: 1
Views: 128
Reputation: 193271
You can't just return from asynchronous operation like AJAX request. In your case currentSurvey.sweep
returns a Promise object, so you should use its API to chain callback with then
method. This callback will be invoked once data is available:
messages.sweep('1').then(function(response) {
$scope.result = JSON.stringify(response.data);
});
Another thing, you don't really need to provide messages
key in resolve section of the router config. You can inject currentSurvey
service directly to controller.
Upvotes: 1