0

I am trying to create a service, and this is it:

(function () {
 'use strict';
 angular
 .module('app')
 .factory('appService', Service);
 function Service($http) {
 function getData() {
 var request = new XMLHttpRequest();
 request.open('GET', 'mock.json', false);
 request.send(null);
 return [request.status, request.response, {}];
 }
 return {};
 }
})();

Where mock.json is in the same folder.

Then I try to call it from a controller:

(function () {
 'use strict';
 angular.module('app')
 .controller('appCtrl', appCtrl);
 /** @ngInject */
 function appCtrl(appService) {
 console.log(appService.getData());
 }
})();

But it gives me an error:

TypeError: appService.getData is not a function

What am I doing wrong?

asked Dec 21, 2016 at 12:22

2 Answers 2

4

You are returning empty object, thus you are getting the expected error.

function Service($http) {
 function getData() {
 var request = new XMLHttpRequest();
 request.open('GET', 'mock.json', false);
 request.send(null);
 return [request.status, request.response, {}];
 }
 //Here return the function reference of getData
 return {
 getData : getData
 };
}
answered Dec 21, 2016 at 12:24
Sign up to request clarification or add additional context in comments.

Comments

1

You are just missing to return the object with the proper properties on your Service

return {
 getData: getData
}
answered Dec 21, 2016 at 12:26

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.