AngularJS dual-stage resolution for resolving dependencies

I am facing a scenario where I must resolve one item before obtaining the data necessary to resolve another:

      .state('addtrip', {
        url: '/addtrip',
        templateUrl: 'views/addtrip.html',
        controller: 'AddtripCtrl',
        resolve: {
          auth : function($state, Auth){
            return Auth.$requireAuth().then(function(auth) {
              return Auth;
            }, function(error){
              $state.go('login');
            });
          },
          trips : function(rootRef,$firebaseArray){
            return $firebaseArray(rootRef).child(auth.uid).$loaded();
          }
        }

Essentially, I need to first retrieve the auth object and only then fetch the trips for that specific user.

Any suggestions on how to best handle such situations?

Answer №1

It appears that the individual mentioned above neglected to include a promise return statement in the inner function

.state('addtrip', {
        url: '/addtrip',
        templateUrl: 'views/addtrip.html',
        controller: 'AddtripCtrl',
        resolve: {
          auth :function($state, Auth,rootRef,$firebaseArray,$q){
             return Auth.$requireAuth().then(function(auth) {
               var p = new Promise (resolve, reject)
               resolve({
                 auth: auth,
                 trips:  $firebaseArray(rootRef).child(auth.uid).$loaded();
               });
           return p;
          })
        }

    }
}

Answer №2

Initially, I followed the method outlined on the Firebase website. Subsequently, I incorporated currentAuth and waitForAuth into my trips function. While adjustments were necessary to align it with my program's requirements, I have personally tested this approach and found it to be effective. (Apologies for any formatting issues in the code)

.run(["$rootScope", "$state", function($rootScope, $state) {
    $rootScope.$on("$stateChangeError", function(event, toState, toParams, fromState, fromParams, error) {
        // By detecting the error triggered when the $requireAuth promise is unfulfilled, we can redirect the user to the login page
        if (error === "AUTH_REQUIRED") {
            $state.go("login");
        }
    });
}])


  .state('addtrip', {
    url: '/addtrip',
    templateUrl: 'views/addtrip.html',
    controller: 'AddtripCtrl',
    resolve: {
      "currentAuth": ["firebaseRef", function (firebaseRef) {
                        // The resolve waits for the completion of the $requireAuth promise
                        // If the promise is rejected, it will result in a $stateChangeError (refer above)
                        //return firebaseRef.refAuth().$requireAuth();
                        return firebaseRef.refAuth().$requireSignIn();
                    }],
                    "waitForAuth": ["firebaseRef", function (firebaseRef) {
                        // The resolve waits for the completion of the $requireAuth promise
                        // If the promise is rejected, it will result in a $stateChangeError (refer above)
                        return firebaseRef.refAuth().$waitForSignIn();
                    }],
      trips : function(currentAuth, waitForAuth, rootRef,$firebaseArray){
        return $firebaseArray(rootRef).child(currentAuth.uid).$loaded();
      }
    }

Answer №3

Let's experiment with promise chaining this time. It should definitely work,

  .state('addtrip', {
    url: '/addtrip',
    templateUrl: 'views/addtrip.html',
    controller: 'AddtripCtrl',
    resolve: {
      auth :function($state, Auth,rootRef,$firebaseArray,$q){
          var defer = $q.defer();
          var obj = [];
           Auth.$requireAuth().then(function(auth) {
            obj.push(auth);
            var a = $firebaseArray(rootRef).child(auth.uid).$loaded();
            obj.push(a);
            defer.resolve(obj);
       });
        return defer.promise;
      }
}

Otherwise, you can also try the following approach,

 .state('addtrip', {
        url: '/addtrip',
        templateUrl: 'views/addtrip.html',
        controller: 'AddtripCtrl',
        resolve: {
          auth :function($state, Auth,rootRef,$firebaseArray,$q){
             return Auth.$requireAuth().then(function(auth) {
    return {
            auth: auth,
            trips:  $firebaseArray(rootRef).child(auth.uid).$loaded();
           };
          })
        }

}
        }

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

Searching an array object inside another array object using JavaScript/AngularJS

Here is my issue: I am facing a situation where I have two Array objects as follows var array1 = [{ "id": 1, "name": "potatoe", photo="photo"}, {"id": 2, "name": "budget"}] var array2 = [{ "id": 1, "name": "potatoeModified"},{ "id": 3, "name": "UhOhA ...

Triggering the AJAX function in the main window

My HTML webpage has a hyperlink that, when clicked, opens the same page in another window with a hash value appended to the URL using window.open. For example, the URL could look like this: http://mywebsite.com#hash=value The webpage contains a JavaScript ...

What causes a 500 error when using PHP eval in conjunction with AJAX?

Working within a system where all PHP code resides in a database for dynamic alterations has presented me with an interesting challenge. While the code displays perfectly on the page, calling the same code via AJAX triggers a frustrating error 500. I' ...

Calculate how frequently an element showcases a particular style

I attempted to tally the occurrences of a specific class on an element, but I keep encountering the error message: $(...)[c].css is not a function Does jQuery have it out for me? Below is the code snippet in question: // hide headings of empty lists le ...

fill collections within backbone

Looking to optimize populating a Backbone collection, I have come across the push method but it requires iterating over all items: define([ ... ], function($, _, Backbone, imagesCollection, imageTemplate, gridView) { var AppView = Backbone.View.ex ...

Creating a JavaScript function that generates a heading element

Hey there, I'm just starting out and could really use some guidance. I want to be able to have a function called addHeading() that takes the heading type selected from a drop-down menu and the text inputted in a form field, then creates and displays t ...

The RefreshIndicator from Material-UI fails to display during the first page load

I am facing an issue with displaying a loading icon during the initial page load. The code appears to be correct to me but for some reason, the loading icon is not showing up. I am utilizing the RefreshIndicator component from material-ui for the loading i ...

Leveraging angular-cli built files as a dependency for another angular2 project

Is it feasible to utilize the build artifacts from one angular-cli project in another? For instance, I have created and published project "A", then subsequently created project "B" and added A to its dependencies (node_modules). Currently, these are the ...

Implementing the ternary operator in Laravel blade templates alongside AngularJS version 1.4.8

I have JSON data in the following format - {"Front head room":"38.0 in.","height adjustable driver seat":true,"multi-level heating passenger seat":true,"sport front seats":true,"Front shoulder room":"55.6 in.","multi-level heating driver seat":true,"8 -w ...

Obtaining an OBJECT from a hashmap instead of a string

In my code, I am working with a hashmap and I want to extract all the values from this map without needing to reference a specific key. Here is a basic overview of the process: Create a hashmap using an external file with a structure of "id:value" Utili ...

Occasionally, the function XMLHttpRequest() performs as expected while other times it may

I've encountered an issue with my XMLHttpRequest() function where it randomly works in both Chrome and IE. The function is triggered by On-click, but I'm having trouble catching the error. The only information I could gather is that readystate = ...

String variable representing the name of a React element

As I was reviewing the source code of a React UI library, I stumbled upon an interesting code pattern that I will simplify here: function Test() { let Button = "button"; // ... return <Button>Click me</Button>; } I'm curious about ...

Swapping out nodes for images using d3.js

Below is the code snippet I am currently executing http://jsfiddle.net/a7as6/14/ I have implemented the following code to convert a node to an image: node.append("svg:image") .attr("class", "circle") .attr("xlink:href", "https://github.com/favico ...

Angular 7 features a table with multiple timers indicating the remaining time until expiration

I have a table with multiple rows where I need to display a timer showing the remaining time in days, hours, minutes, and seconds. After researching how to calculate the remaining time using this link, I found a solution that works well. I am calling the ...

How can I ensure the screen is cleared before the next frame in three.js?

While working in Three.js WebGLRenderer, I understand that using context.clearRect() requires a canvas and other elements. However, my question is: How can I achieve the same functionality as clearRect in Three.js WebGLRenderer? In my game, a JSON model i ...

Why is the state object empty in this React Native function?

One React-Native component I have is responsible for rendering an image gallery in a list format. This component is called once for each item on the parent list. It takes two props: "etiqueta," which contains the title of the item, and "galleries," which i ...

How to turn off and on all elements within a Div tag

Is there a way to disable all elements within a Div tag? I've managed to disable input types successfully, but I'm struggling with links. I attempted the solution provided here, but it didn't work. Here's the code snippet that worked f ...

What are the security benefits of using Res.cookie compared to document.cookie?

When it comes to setting cookies to save data of signed in members, I faced a dilemma between two options. On one hand, there's res.cookie which utilizes the Express framework to set/read cookies on the server-side. On the other hand, there's d ...

Prevent users from clicking by using a CSS class in HTML and JavaScript

,hey there buddy 1° Can you help me figure out how to prevent click behavior using the CSS class? 2° I'm unable to add an ID to the HTML element, so I need to use the Class to achieve this. 3° None of my attempts have been successful so far. El ...

Display the default child of vue-router 4

Need Assistance with Rendering Default Child View in Vue I am currently facing an issue with rendering the default child view for the Category view. I have come across a similar problem discussed on Stack Overflow, but it seems to be related to VUE2 and o ...