Fulfill the promise within the $stateProvider and proceed with utilizing the outcomes

I am facing an issue where I need to resolve a promise in a state provider so that I can use the results of the promise in another promise.

I am a bit unsure about how to go about this. I tried the following approach:

 app
    .config(['$stateProvider','GeolocationService',
      function($stateProvider,geolocation){
        $stateProvider.state('sendCoords',{
          resolve: {
            long: function (geolocation) {
              geolocation().then(function (position) {
                return position.coords.longitude;
              }, function (reason) {
                return false;
              })
            },
            lat: function (geolocation) {
              geolocation().then(function (position) {
                return position.coords.longitude;
              }, function (reason) {
                return false;
              })
            }
          },
          controller: 'appCtrl'
        })

      }
    ]);

However, I am not sure if this implementation is correct. I want the geolocation to be resolved first and then use the 'lat' and 'long' variables in my controller.

app.controller('appCtrl',['$scope','serviceTest',function($scope,serviceTest,lat,long){
       $scope.optionsToChoose = [];
        serviceTest.options(long,lat).then(
          function (option) {
            $scope.optionsToChoose = option;
          },
          function(error){
          }
        );
}]

When I try to inject lat and long like this, they end up being undefined. I am aware that I have made some mistake, but I am struggling to identify it. Any help would be greatly appreciated.

EDIT: Here is the Geolocation Service Code

app.factory("GeolocationService", ['$q', '$window', '$rootScope',
  function ($q, $window, $rootScope) {
    return function () {
      var deferred = $q.defer();

      if (!$window.navigator) {
        $rootScope.$apply(function() {
          deferred.reject(new Error("Geolocation is not supported"));
        });
      } else {
        $window.navigator.geolocation.getCurrentPosition(function (position) {
          $rootScope.$apply(function() {
            deferred.resolve(position);
          });
        }, function (error) {
          $rootScope.$apply(function() {
            deferred.reject(error);
          });
        });
      }

      return deferred.promise;
    }
  }]);

Answer №1

angular-ui-router allows for passing "resolved" values into other functions that need to be resolved. Following @charlietfl's helpful recommendation, I will resolve the longitude and latitude as a combined object:

resolve: {
  position: function(GeolocationService){
    return GeolocationService().then(function(position){
      return { long: position.coords.longitude,
               lat:  position.coords.latitude };
    });
  },
  options: function(serviceTest, position){
    return serviceTest.options(position.long, position.lat)
                      .then(function(option){ return option; });
  }
}

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 best way to retrieve an ID from a select multiple using Element?

I am working on a select element for assigning persons to a project. My goal is to send the ID of the selected person object to a specific function. Here is what I have tried so far: <el-form-item label="Assign to:" prop="person"> & ...

The $scope variable is missing from the DOM

I've been trying to implement ng-repeat with AngularJS, but I'm having trouble getting the scope result in my DOM. Is there something wrong that anyone can spot? I've spent hours troubleshooting this and no matter what I do, "players" always ...

Adjust the position of the footer up or down based on changes in page content height

If I have jQuery at my disposal, how can I achieve the following task? There is a div on the page with dynamic content and no fixed height. The height of this div changes as users type and content appears or disappears accordingly. Although everything is ...

Struggling with displaying nested JSON data in React components

I have a nested JSON structure running on my local server, and I'm using React to practice displaying this nested data. Currently, I am focusing on showing the day and the available time slots for that day. I have managed to extract the "days" (mon, t ...

Deciphering a JSON array by value or key

I have a JSON array that I need to parse in order to display the available locations neatly in a list format. However, I am struggling with where to start. The data should be converted to HTML based on the selected date. In addition, a side bar needs to s ...

Ways to prompt for user input using JavaScript

How can I collect user input using JavaScript for a website that saves the input into a text file? Below is the code I am currently using: <button type="button" onclick="storeEmail()">Enter Email</button> <script> ...

"Error: Unable to access the property '$emit' of an undefined value" - VueJS

I'm currently working on implementing a basic authentication system in vuejs. I have a set of objects containing valid usernames and passwords. I am looping through this list to validate the entered username and password. If there is a match, I trigge ...

Encountering an "Angularjs 1.2.x Injector:modulerrr" error, even after successfully incorporating ngRoute

I am currently learning angularjs and I have encountered a persistent error. Despite multiple attempts at troubleshooting, I have been unable to resolve it. Here is the code that I have: index.html <!doctype html> <html ng-app="myApp"> <he ...

Steps to disable all fields if the previous field is set to its default value and the default value is currently selected

As a newcomer to AngularJS, I have successfully disabled fields based on previous field selections. However, my goal is to set the default value of "ALL" for all fields (country, state, city). If the country value is set to "ALL," then the state and city ...

What is the best way to determine which id has been clicked using jQuery?

Can someone help me figure out how to determine which button has been clicked using jQuery? Here is the HTML code I am working with: <div class="row"> <div class="col-md-6"> <div class="well " id="option_a"> </div& ...

What is the best way to access a specific attribute of an HTML element?

Within my ng-repeat loop, I have set a custom attribute like this: <div ng-repeat="item in itemsList" stepType="{{item.stepType}}"> {{item.itemValue}} </div> The possible values for item.stepType are 'task' or 'action ...

Transferring a variable from an Angular 2 constructor into the template via the then statement

I'm struggling with implementing a secure login system. My goal is to first check the device's native storage for an item named 'user', then verify if the user exists in our database, and finally retrieve the unique id associated with t ...

Interacting with the header component within the renderHeader property of the MUI Data Grid Pro will update the sortModel

Currently, I am utilizing the Material UI DataGridPro component to construct a React Js application. I am interested in developing a customized filtering feature. In the image below, you can see a red box representing an IconButton for the filtering view ...

What is the best way to insert a permanent script tag into the body of a Gatsby site? Can conditional rendering be used to control

As an illustration: - const nation = "USA" import chat from './utils/script'; // script is imported from a file if(nation === "USA") // utilized conditionally in the component { chat } else { console.log("Not USA") } inform me witho ...

Ways to resolve a 500 internal error

I have created an online test system for students, but I am facing an issue with passing answers in JSON format. Whenever I attempt to do so, I encounter a 500 internal error and I am unable to identify the root cause. Even after removing lengthy JSON dat ...

What is the reason behind this being deemed as true?

Imagine we have this snippet of code: var attachRed = false; Why is attachRed = !attachRed equivalent to true? I'm curious because I'm working with Vue.js and trying to grasp why this particular piece of code functions as it does. <div id= ...

Ensure that the main div remains centered on the page even when the window size is adjusted

Here is the code snippet: <div id="root"> <div id="child1">xxxx</div> <div id="child2">yyyy</div> </div> CSS : #root{ width: 86%; margin: 0 auto; } #root div { width: 50%; float: left; border: ...

Anchor element not displaying Bootstrap popover upon focus trigger

I'm exploring ways to implement bootstrap popovers that respond to both click and hover events without relying on jQuery. I have a variety of controls on my page and I want to bind popovers to them using JavaScript. While testing with buttons and anc ...

State variables in React hooks like useState always return the previous value before

Whenever I choose a value, it seems to always display the previously selected option instead of the current one. What I really want is for the selection to update and store the current value immediately. const [postsPerPage, setPostsPerPage] = useState(1 ...

javascript - The window.onload event is not firing

I am currently working on developing a tool that will allow users to export a PDF file. There are two scenarios to consider: The first scenario involves a straightforward process where the user clicks the export button, and a new blank window opens imm ...