Retrieving information from an Angular service using a specified function

I have been working on accessing data from a method within a service that returns coordinates, which are used to make HTTP requests in my application. I have integrated my Leaflet code into the controller to be able to access the lat,lng coordinates for making API requests to another API. Although everything seems to be functioning fine, I am encountering an issue when trying to pass this data to the controller as it does not recognize the property "L.Control.Search". Additionally, I tried creating an array and accessing it within the controller, but it consistently returned undefined.

   app.service('mapService', (function($http,$q) {
    //Coordinates
    var fmCoordinates = {};
    //Function to Request markets
    var requestMarkets = function(lat,lng){
        var defer = $q.defer();
        var dataFromHttp = {};
        var options = {
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: "http://someurl?lat=" + lat + "&lng=" + lng
        };
        $http(options).then(function(result) {
           dataFromHttp = result.data;
           defer.resolve(dataFromHttp);
       }, function(error){
           defer.reject(error);
       });
       return defer.promise;
    };

    L.Control.Search = L.Control.extend({

    _getLocation: function(key) {   //extract latlng from _recordsCache

        var latLong = this._recordsCache[key];
        console.log("This is latlong:\n"+Object.keys(latLong));
        fmCoordinates.lat = latLong.lat;
        fmCoordinates.lng = latLong.lng;
        console.log(fmCoordinates.lat,fmCoordinates.lng || "Nothing yet!");
        var promise = requestMarkets(fmCoordinates.lat,fmCoordinates.lng);
        promise.then(function(greeting) {
            for(var property in greeting.results) {
                console.log(property + "=" + greeting.results[property]);
            };
            console.log('Success: ' + greeting.results);
        }, function(reason) {
            console.log('Failed: ' + reason);
        });
        if( this._recordsCache.hasOwnProperty(key) )
            return latLong;//then after use .loc attribute
        else
            return false;
    },

    L.Map.addInitHook(function () {
        if (this.options.searchControl) {
            this.searchControl = L.control.search(this.options.searchControl);
            this.addControl(this.searchControl);
        }
    });

    L.control.search = function (options) {
        return new L.Control.Search(options);
    };

}));

Answer â„–1

Your code for handling promises seems to have a slight issue. Make sure to make the necessary adjustments as the promise should be resolved before returning.

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

};

Additionally, make sure there is consistency in naming conventions, such as using either l.Control.Search or L.control.search throughout your codebase.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Concealing a DIV element when the value is not applicable

I'm currently working on a website for a coffee shop product. On this site, each product has a coffee strength indicator that is determined by the database. The strength can be categorized as Strong, Medium, Weak, or n/a (for non-coffee products). If ...

Utilizing NextJs req.query parameter in Prisma for advanced query filtering

Currently, I am delving into the world of NextJS and experimenting with sending requests to an API while passing a parameter that is then used by Prisma to query the database. In order to achieve this, I've created a new file located at /api/posts/[s ...

Boost Google Pagespeed score by reducing 'Total Blocking Time' in NextJs

I've recently started using NextJS and I'm looking to improve my Google Pagespeed ranking. So far, I've made some good progress in optimizing different metrics. From the screenshot provided, it's clear that the only issue remaining i ...

"AngularJS directive mandating the use of the required attribute for internal control

I've encountered a challenge with this specific issue. We are using a directive called deeplink, which contains the following code: restrict: 'E', require: 'ngModel', scope: { smDropdown: '=smDeeplinkDropdown', s ...

Highcharts real-time data not refreshing following modification of PHP variable

Currently, I have a live updating highchart implemented on a webpage named index.html. This highchart calls a PHP script called datatest.php to parse a CSV file, convert the data into JSON format, and then add it as a new point on the chart: $.ajax({ ...

Compare several objects or arrays based on a selected array and combine them into a single object containing all matching elements from the selected array

selection = ["A", "lv3", "large"] Data = [{ id:1, title:"this is test 1", category:"A, D", level:"lv5", size: " medium", }, id:2, title:"this is test 1", category:"C ...

Check the schedule for any upcoming events

I am currently designing a website for a friend and I have a question regarding the functionality of the FullCalendar jQuery plugin. Is there a way to determine if there is an event scheduled for today using FullCalendar? If so, I would like to display t ...

Execute a PUT request within a Firebase Cloud Function database handler

I am working on syncing data between my server's database and Firebase realtime db. The first part, which involves syncing from my server to Firebase, is already complete. However, I am facing challenges with the second part - syncing data from Fireba ...

Having trouble loading data.json file in React.js and jQuery intergration

Having a background in mobile development, I am relatively new to web development so please excuse any amateur questions. Currently, I am working on a react.js project using create-react-app (which utilizes Babel). I am following a tutorial that requires ...

The functionality of Angular.js ajax and apply is experiencing technical difficulties

As I venture into the world of angular.js, I am facing a challenge with displaying the correct content on my website. The pages' content is fetched via AJAX (currently from static data, but eventually from a database). When I place a block with the ng ...

What is the mechanism of `this` in higher order components?

I am delving into the concept of higher order components by exploring this online resource. However, I am struggling to grasp how this is utilized within one. Am I correct in thinking that the this in the constructor refers to what will ultimately be retur ...

ng-options do not refresh automatically when modifying elements in the array

Having trouble updating the data in a select list? It seems that when selecting 'test', the value retrieved from the API is 'ÅšlÄ…sk' even though it's not listed. For example: I select 'test' but it shows as 'ÅšlÄ ...

Why isn't the length of the Array changing when using React's useState hook

I am facing a challenge trying to understand why the value of inputElementArray.length consistently remains 0 when accessed within the useEffect method. function view() { const [inputElementArray, setInputElementArray] = useState<HTMLInputElement[]& ...

Checking for different elements between two arrays in AngularJS can be achieved by iterating through

I am working with two arrays: $scope.blinkingBoxes=[1,3,2] In addition, I have another array named $scope.clickedBoxes where I push several values. Currently, I use the following code to determine if the arrays are identical: if(angular.equals($scope.bli ...

Error in THREE.js: Failed to retrieve object at http://192.168.8.104:8080/[object%20Object] (Error code: 404) - Module: three.module.js

During my attempt to create a text loader in THREE.js, I encountered an error instead of getting the expected text output. three.module.js:38595 GET http://192.168.8.104:8080/[object%20Object] 404 (Not Found) I made various efforts to resolve this error ...

Prevent clicking on form until setInterval has been cleared using React useEffect

Here is a link to a sandbox replicating the behavior: sandbox demo I have integrated a hook in a React component to act as a countdown for answering a question. React.useEffect(() => { const timer = setInterval(() => { setTimeLeft((n ...

Synchronizing two navigation menus on a single-page application website

Let me start by saying that I specialize in back end development and am facing a specific challenge with building a website that includes two navigation menus. The main navigation menu features links like Home, while the sub-navigation menu includes option ...

Looking for assistance in creating an html page with a rotating CSS div containing unordered lists and list items

I am sharing the HTML content of my test page that I am looking to customize similar to some websites I have come across. My goal is to create a rotating div with an unordered list (ul li), where only three divs are displayed at a time while the rest remai ...

The button fails to log any text to the developer console

Attempting to verify the functionality of my button by logging a message on the developer console. However, upon clicking the button, the text does not appear in the console. import { Component, EventEmitter, Input, Output } from '@angular/core'; ...

Passing and removing array parameters in HTTP requests using Angular

I have an Array of statuses objects. Each status has a name and a boolean set to false by default. These represent checkboxes in a form with filters - when a checkbox is checked, the boolean value is set to true: const filters.statuses = [ { name ...