Ian Steffy
Ian Steffy

Reputation: 1234

service gets URL for $http API request from controller - Angular.js

I want a service that grabs info from an API but only after clicking an HTML element.

"freegeoip.net/json/" + ip_address

The problem is, my service and URL above is being called before the click occurs.

app.service("ips", function ($http, $q)
{
    // Grab json
    var deferred = $q.defer();
    $http.get("http://www.freegeoip.net/json/" + ip_address).then(function (data)
    {
        deferred.resolve(data);
    });

    this.getItems = function ()
    {
        console.log(deferred.promise);
        return deferred.promise;
    }
})

Can someone show me I can define this variable ip_address later in a click?

///Inside the controller

promise.then(function (data)
{
    $scope.items = data.data.items;
});
$scope.defineIP= function(item)
{
   ip_address = "212.38.168.60"
   return ip_address;
}

The problem here is that I have no clue how to take this value i defined for ip_address and inject it into the service.

Upvotes: 0

Views: 53

Answers (2)

user1608841
user1608841

Reputation: 2475

Your Code should go like this.

app.service("ips", function ($http) {
    this.getItems = function (ip_address) {
       return  $http.get("freegeoip.net/json/" + ip_address)
    }
});

and in controller :

$scope.defineIP= function(){
   var ip_address = "212.38.168.60"
   ips.getItems(ip_address).then(function(response){
     console.log(response);
   }) 
}

Dont forget to add "ips" as DI in controller.

As you want to grab info on click of HTML element then you should call like below:

 <button ngClick="defineIP()">Click Here</button>

You dont need to inject $q in service as $http returns you the Promise Object so that you can use .then() method directly in controller

Upvotes: 2

Indhu
Indhu

Reputation: 399

The $http request will be called once u inject the service. So you should be called like this.

app.service("ips", function ($http, $q)
{
    // Grab json    

    this.getItems = function (ip_address)
    {
        var deferred = $q.defer();
        $http.get("freegeoip.net/json/" + ip_address).then(function (data)
        {
          deferred.resolve(data);
        });
        return deferred.promise;
    }
})

In controller:

var promise = ipsService.getItems(ip_address);

Upvotes: 0

Related Questions