Utilizing AngularJS Scopes in Conjunction with Additional Services

Currently, I am working on a project using AngularJS and encountering difficulties with my services. I have developed a service that provides two functions - one to retrieve the user's current location and another to fetch an API URL. The issue lies in the fact that the API URL requires latitude and longitude coordinates. I aim to extract the current location data and inject it into the URL for data binding purposes in my view. How do I establish scope references between these services?

angular.module('myApp', [])

.controller('HomeCtrl', ['$scope', '$q', '$http', 'myService',
  function($scope, $q, $http, myService) {

    myService.getLocation().then(function(data) {
      $scope.lat = data.coords.latitude;
      $scope.long = data.coords.longitude;
      console.log($scope.lat, $scope.long);
    });
    myService.getAirports().then(function(data) {

    });
  }
])

//MYSERVICE FACTORY
.factory('myService', function($http, $q, $cordovaGeolocation) {
  return {
    getLocation: function() {
      var deferred = $q.defer();
      $cordovaGeolocation.getCurrentPosition().then(function(position) {
        var lat = position.coords.latitude;
        console.log(lat);
        deferred.resolve(position)
      });
      return deferred.promise;
    },


    getAirports: function() {
      var deferred = $q.defer();
      var url = 'https://api.flightstats.com/flex/airports/rest/v1/jsonp/withinRadius/' + PLACE LONGITUDE HERE + '/' + PLACE LONGITUDE HERE + '/10?appId=02a5e867&appKey=1f2075112529890985b1dd8ea0f0a419' + '&callback=JSON_CALLBACK';
      var config = {
        method: 'GET',
        callback: 'JSON_CALLBACK'
      }
      $http.jsonp(url, config)
        .then(function(data) {
          var lat = data.data.airports[0].latitude;
          deferred.resolve(data)
        });
      return deferred.promise;
    }
  }
});

Link to JSFiddle

If you have any suggestions on simplifying my code, please feel free to share them.

Answer №1

To effectively retrieve data from both services, it is recommended to nest the call to the second service within the then method of the first service and provide the necessary lat/lng information:

myService.getLocation().then(function(data){
    $scope.lat = data.coords.latitude;
    $scope.long = data.coords.longitude;
    console.log($scope.lat, $scope.long);
    myService.getAirports($scope.lat, $scope.long).then(function(data){

    });
});

This approach allows seamless utilization of the retrieved data in the getAirports method:

getAirports: function(lat, lng) {
 ....
 var url = 'https://api.flightstats.com/flex/airports/rest/v1/jsonp/withinRadius/'+ lat+'/'+lng+'/10?appId=02a5e867&appKey=1f2075112529890985b1dd8ea0f0a419' + '&callback=JSON_CALLBACK';
 ....
}

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

What is the reason for HereMap factoring in stopOver time when calculating travel time for the destination waypoint?

I am currently working on a request using the HereMap Calculate Route API. Waypoint 0 does not have any stopOver time, but waypoints 1 and 2 do have stopOver times. Below is an example of the request: https://route.ls.hereapi.com/routing/7.2/calculateroute ...

What is the process for sending JavaScript data to a Rails controller action?

Utilizing jQuery Shapeshift for drag and drop reordering of lists on my web application. I am looking to send the data below to my Rails controller action in order to update the list's order. Every time I drag a list, this is the output that appears ...

What is the best way to save the $stateparams parameter value in Angular Js after refreshing the page?

When a button is clicked, the state changes from one state to another. To pass the Id value, I am using ui-sref. This is how I declare my button with an id: <button ui-sref="list({id:'{{id}}'}"></buton> Within the state, I receive t ...

Place a <div></div> element within a collapsible accordion container that conceals the content inside the <div>

My accordion is expanding, but the div inside it appears blank instead of displaying its content. Any suggestions on how to fix this? Thank you. How can I ensure that the div inside the accordion shows its content? Here is the code: http://jsfiddle.net/6 ...

Is there a way to rearrange the selectpicker selection based on the user's choice?

I'm in the process of setting up a selectpicker that allows users to choose multiple options from a dropdown list. The challenge is that the values extracted by my backend need to be in the order of user selection, rather than the original order of th ...

Guide to fetching React into background.js of a Chrome extension

I'm trying to implement reactDOM for injecting content onto a webpage. Here is the code snippet I have: import React from 'react'; ... import App from './src/js/App'; const root = createRoot(document.getElementById('title&apo ...

Exciting method for transferring URL parameters in AngularJS

$http({method: 'GET', url: '/asas/asasa'}).success(function(data) { $scope.website = data.websites; $scope.topoffer = data.coupons; $scope.webcall = function () { $http({method: 'GET',url: &a ...

Internet Explorer is failing to send the success function in AJAXFORM

After creating this ajaxform function with a success function that triggers when the form is submitted, I discovered an issue: the ajaxform functions perfectly in all browsers except for IE. The baffling part is why IE fails to pass the function. AjaxForm ...

Executing multiple concurrent progress lines in the Node.js console using Node.js Puppeteer

I developed a basic script that automates file uploads on a website. Utilizing puppeteer for headless browsing, I handle login and file uploading processes. To track changes in the upload progress bar, I have implemented a mutation observer injected into t ...

Ensuring a correct dismount of a React component

Apologies for the lack of specificity in the title of this inquiry. Upon executing the code snippet below, I encountered the ensuing warning: Warning: setState(...): Can only update a mounted or mounting component. This typically indicates that you call ...

What is the best way to obtain the SearchIDs for various searchNames using JavaScript?

Who can assist me in resolving this issue? I am trying to retrieve the id of a searchName whenever a user selects the checkbox. Ideally, I would like to assign the value of the PHP line $search_row->searchid to the id attribute in the input field. Apolo ...

The expo-location feature is failing to accurately record and store all of the positions within the array

Incorporating expo-location in my react-native app, I utilize it to track the user's positions and store them in a redux object. While debugging the object reveals that all positions have been successfully inserted, upon retrieving this array, it turn ...

Guide on attaching a function to an Element that is dynamically loaded using Ajax

Including multiple Divs with the CSS class "hello" on my page. I then utilize Ajax to retrieve additional Divs also with the CSS class "hello". This leads to a code snippet being triggered upon clicking the Divs: $('.hello').click(function(){ ...

Is it possible to reduce a field value in firestore after successfully submitting a form?

I have a variety of items retrieved from firestore: availability : true stocks: 100 item: item1 https://i.stack.imgur.com/hrfDu.png I am interested in reducing the stocks after submitting a form. I used the where() method to check if the selected item m ...

A guide to pulling pictures from a database with the help of jquery and servlets

Currently, I am facing a challenge in retrieving images stored in my Oracle 11g R2 database. My approach involves using JQuery and servlet to fetch the images and displaying them within a CSS division. However, as I am unfamiliar with this process, I bel ...

Guide to adding table classes to AJAX response tables

I am facing an issue with displaying data in a table based on the AJAX request made. The problem arises because the data displayed does not follow the pagination classes applied to the table. My table has pagination functionality where 10 records are shown ...

AngularJS: How to handle promise returned by 'Collector' service in order to pass value within function?

My Collector service is designed to manage models by interacting with localStorage and the server. The function Collector.retrieveModel(uuid) retrieves a model from the collector, first checking if it exists in localStorage, then requesting it from the ser ...

Issue with Responsive Font Size functionality in Tailwind and ReactJS not functioning as expected

I'm really struggling with this issue. I grasp the concept of mobile-first design and have successfully made my website's layout responsive. However, I'm having trouble getting the font size to change when applying breakpoints as the screen ...

Imported function encounters a non-function error

I'm encountering a puzzling reference/binding error that I can't seem to resolve: import React from 'react'; var { View, StyleSheet, Alert, AsyncStorage } = require('react-native'); import {Button} from 'react-native-el ...

Receiving multiple Firebase notifications on the web when the same application is open in multiple tabs

I have implemented firebase push notifications in Angular 7 using @angular/fire. However, I am facing an issue where I receive the same notification multiple times when my application is open in multiple tabs. receiveMessage() { this.angularFireMess ...