0

I am using below function to loadbenefittypes.

my get data function

$scope.loadCashBenefitTypes = function (){
 $http({
 method: "GET",
 headers: {
 'Content-Type': 'application/json',
 'Authorization': 'Bearer ' + localStorage.getItem('JWT_TOKEN')
 },
 url: appConfig.apiUrl + "/benefit-types/income?income_type=Cash Benefit",
 }).then(function (response) {
 $scope.func1 = response.data
 }, function (response) {
 });
}

i am using above function to load benefit types in multiple locations in my application. therefore i need to reuse this function as a service. how i convert above function and how i assign it to different drop down models

georgeawg
49k13 gold badges78 silver badges98 bronze badges
asked Mar 19, 2020 at 2:19
1
  • You can just move this function in factory /service and return this function from your factory/ service and reuse in multiple component / directive/ controller.You can refer docs.angularjs.org/guide/services for more info. Let me know if you need the code as well for same . Commented Mar 19, 2020 at 2:37

1 Answer 1

1

To re-factor the code to a service, return the $http promise:

app.service("myService", function($http, appConfig) {
 this.getCashBenefitTypes = function (){
 return $http({
 method: "GET",
 headers: {
 'Content-Type': 'application/json',
 'Authorization': 'Bearer ' + localStorage.getItem('JWT_TOKEN')
 },
 params: { income_type: 'Cash Benefit' },
 url: appConfig.apiUrl + "/benefit-types/income",
 }).then(function (response) {
 return response.data;
 });
 } 
});

Then inject that service in the controllers:

app.controller("app", function($scope, myService) {
 myService.getCashBenefitTypes()
 .then(function(data) {
 $scope.types = data;
 }).catch(response) {
 console.log("ERROR", response);
 });
});

For more information, see

answered Mar 19, 2020 at 10:04
Sign up to request clarification or add additional context in comments.

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.