2
\$\begingroup\$

I have multiple API calls so I created a service however I would like to find a way to remove the duplication

myAppServices.factory('apiService', function ($http, $q) {
 return {
 getDocuments: function () {
 return $http.get('/api/autodeskdocuments/1')
 .then(function (response) {
 if (typeof response.data == 'object') {
 return response.data;
 } else {
 // invalid response
 return $q.reject(response.data);
 }
 }, function (response) {
 // something went wrong
 return $q.reject(response.data);
 });
 },
 getSharePoint: function () {
 return $http.get('/api/sharepointheaderdata/1')
 .then(function (response) {
 if (typeof response.data == 'object') {
 return response.data;
 } else {
 // invalid response
 return $q.reject(response.data);
 }
 }, function (response) {
 // something went wrong
 return $q.reject(response.data);
 });
 }
 };
});

As you can see both functions has some duplication with the .then(...) Any suggestions as to make this cleaner?

asked Feb 11, 2015 at 2:56
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

You can extract the whole ajax to a function.

myAppServices.factory('apiService', function ($http, $q) {
 var get = function(endpoint) {
 return $http.get(endpoint)
 .then(function (response) {
 if (typeof response.data == 'object') {
 return response.data;
 } else {
 // invalid response
 return $q.reject(response.data);
 }
 }, function (response) {
 // something went wrong
 return $q.reject(response.data);
 });
 }
 return {
 getDocuments: function () {
 return get('/api/autodeskdocuments/1');
 },
 getSharePoint: function () {
 return get('/api/sharepointheaderdata/1');
 }
 };
});
answered Feb 11, 2015 at 18:59
\$\endgroup\$
1
  • \$\begingroup\$ wow, thanks... that makes more sense and so much cleaner! \$\endgroup\$ Commented Feb 11, 2015 at 19:16

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.