0

I am using AngularJS leaflet to search for a location and obtain latitude and longitude coordinates. In my service, I am calling my code to display map with within the service I wrote a callback which takes (lat,lng) and make an HTTP requests to url to get data related to those coordinates.

Ideally, I would like to have created a function that returned an http request and returns the promise in the controller. The problem is that getMarkets is a callback and I can not call .then on the function directly because it needs to be passed the coordinates first. It is returning the data and I would like to know how to pass the data I receive from ($http(options)) to the controller so I can render response in the view.

app.service('mapService', (function($http) {
    var fmCoordinates = {};

    var requestMarkets = function(lat,lng){
        var options = {
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: "http://somerul?lat=" + lat + "&lng=" + lng
        };
        return console.log($http(options));

    };


L.Control.Search = L.Control.extend({
//Leaflet Code
_getLocation: function(key) {   //extract latlng from _recordsCache
        var latLong = this._recordsCache[key];
        fmCoordinates.lat = latLong.lat;
        fmCoordinates.lng = latLong.lng;
        requestMarkets(fmCoordinates.lat,fmCoordinates.lng);
        if( this._recordsCache.hasOwnProperty(key) )
            return latLong;//then after use .loc attribute
        else
            return false;
    },
})
Roscoe
  • 169
  • 3
  • 15

1 Answers1

0

https://docs.angularjs.org/api/ng/service/$q

var requestMarkets = function(lat,lng){
    var defer = $q.defer();
    var dataFromHttp = {};
    var options = {
        type: "GET",
        contentType: "application/json; charset=utf-8",
        url: "http://somerul?lat=" + lat + "&lng=" + lng
    };
    $http(options).then(function(result) {
        dataFromHttp = result.data;
        defer.resolve(dataFromHttp);
    }, function(error){
        defer.reject(error);
    });
    return defer.promise;

};

Then inside of _getLocation

var promise = requestMarkets(fmCoordinates.lat,fmCoordinates.lng);
promise.then(function(yourData){...}, function(error){...});
Passersby
  • 1,092
  • 9
  • 11
  • Thanks. This returns the promise inside of the service. The problem I can not access getLocation. It is inside of this object: L.Control.Search = L.Control.extend({ includes: L.Mixin.Events, getLocation();}); Inside the controller, it does not recognize "Control" – Roscoe May 25 '16 at 18:05
  • Please avoid deferred anti pattern and use `return $http(opts)` – Muli Yulzary Jun 29 '16 at 15:44