Search code examples
javascriptangularjsangular-services

How to pass url as parameter to ajax method that is in a service in Angular js


I am planning to have a separate service for ajax calls. I am trying to call that service from another service, but I want the URL to be passed in via a parameter to the method.

Here is my code:

angular.module("Data", []).service("DataService", function ($http) {
    return {
        Data: function (callback) {
            $http.get('http://www.w3schools.com/angular/customers.php').success(callback);
        }
    }
})

angular.module("Home", ["Data"]).service("HomeService", function (DataService) {
    var customerData = {}
    return {
        Getdata: DataService.getCustomers(function (results) {
            customerData = results;
            console.log(customerData)
        })
    }
})

I don't want to hardcode my URL. Instead, I want it to be passed in as a parameter.


Solution

  • Basically, pass the url to your service method.

      angular.module("Data", []).service("DataService", function ($http) {
    
    
            return {
                getCustomers: function (url, callback) {
                    $http.get(url).success(callback);
                }
            }
        })
    
    
    angular.module("Home", ["Data"]).service("HomeService", function (DataService) {
    
            var customerData = {}
    
            return {
                Getdata: DataService.getCustomers('http://www.w3schools.com/angular/customers.php', function (results) {
                    customerData = results;
                    console.log(customerData)
                })
    
            }
        })