简体   繁体   中英

write angular js service to access multiple function

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM