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

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.