Resolving Meteor collections in the ui-routerIncorporating

My goal is to utilize meteor angular js ui-router resolve to fetch information of a user selected from a user list.

$stateProvider
    .state('userprofile', {
        url: '/user/:userId',
        cache: false,
        template: '<user-profile userinfo="$resolve.userinfo"></user-profile>',
        controller: UserProfile,
        controllerAs: name,
        resolve: {
            userinfo: function($stateParams) {
                viewedUser = Meteor.users.findOne({
                    _id: $stateParams.userId
                });

                return viewedUser;
            },
        }
    });

The issue is that, upon the initial load from the user list, the user profile displays correctly. However, upon page reload, the userinfo becomes undefined. My assumption is that on subsequent loads, the controller is already loaded before the resolve is completed?!

After some research, I experimented with $q and $timeout

        resolve: {
            userinfo: function($stateParams, $q, $timeout) {
                deferred = $q.defer();

                $timeout(function() {
                    deferred.resolve(Meteor.users.findOne({
                        _id: $stateParams.userId
                    }));
                }, 1000);

                return deferred.promise;
            },
        }

As expected, this approach works and the user profile is displayed every time I refresh the page. However, when I reduce the delay to 500, it goes back to being undefined upon refresh. I'm not certain why, in this scenario, a longer delay works?

Thank you!

Answer №1

Below is the snippet of code that I frequently utilize:

resolve: { currentUser: ($q) => { var deferred = $q.defer();

  Meteor.autorun(function () {
    if (!Meteor.loggingIn()) {
      if (Meteor.user() == null) {
        deferred.reject('AUTH_REQUIRED');
      } else {
        deferred.resolve(Meteor.user());
      }
    }
  });

  return deferred.promise;
}

}

This valuable code excerpt comes from a tutorial I stumbled upon by @urigo. It did take some effort to locate, but it functions flawlessly.

For instances where authentication becomes necessary, this code proves to be exceptionally helpful - simply integrate it at the top level within a .run method.

function run($rootScope, $state) {
  'ngInject';

  $rootScope.$on('$stateChangeError',
    (event, toState, toParams, fromState, fromParams, error) => {
      console.log("$stateChangeError: "+error);
      if (error === 'AUTH_REQUIRED') {
        $state.go('login');
      }
    }
  );
}

Answer №2

Below are some routes you can experiment with in the context of resolve:

In the case of using angular-meteor:

resolve: { 
     'loginRequired': function ($meteor, $state) {
                        return $meteor.requireUser().then(function (user) {
                                if (user._id) {return true;}
                            }).catch(function () {
                                $state.go('login');
                                return false;
                            });
                     }
    }

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

Choose the appropriate data type for the class variable (for example, fArr = Uint32Array)

const functionArray: Function = Uint32Array; new fArr(5); The code snippet above is functioning properly. However, TypeScript is throwing a TS2351 error: "This expression is not constructable. Type 'Function' has no construct signatures". I wo ...

Alter the reply prior to being dispatched to the customer

Node 16.14.2, Express 4.18.1 There have been several instances where individuals have altered res.send in order to execute actions before the response is sent to the client. app.use(function (req, res, next) { originalSend = res.send; res.send = f ...

The Gusser Game does not refresh the page upon reaching Game Over

Hi there, I am a beginner in the world of JavaScript and currently working on developing a small guessing game app. However, I have encountered an issue where the page is not reloading after the game is over and the 'Play Again' button appears to ...

Using React and Redux to update a property in the state with a modified array

I am currently developing a React app and utilizing Redux for state management. Below is the code snippet I am working with: menu.actions.js: import { apiUrl, apiConfig } from '../../util/api'; import { ADD_CATEGORY, GET_MENU } from './men ...

Unable to retrieve value 'includes' from null object

Currently, I am utilizing Vue.js along with JavaScript. In my code, there is an array of objects named products, each containing a special property called smallest_unit_barcode. My goal is to filter out only those products that have a barcode similar to a ...

When downloading text using Angular, the file may not display new line characters correctly when opened in Notepad

When downloading text data as a .txt file in my Angular application using JavaScript code, I encountered an issue. Below is the code snippet: function download_text_as_file(data: string) { var element = document.createElement('a') eleme ...

What is the best method for uploading images and form content simultaneously in a Vue application?

How can I simultaneously upload images and form content? Is it possible to upload both to the client first and then to the server together with the form content? I'm looking to submit the form content along with the image to the server in one go when ...

Combining arrays of objects in JavaScript

I am currently working on combining different arrays: const info1 = {id: 1} const info2 = {id: 2} const info3 = {id: 3} const array1 = [info1, info2] const array2 = [info1, info3] const array3 = [info2, info3] const union = [...new Set([...array1, ...arr ...

I am interested in customizing the way data is presented rather than simply storing it with Angular x-editable

Working with Angular X-editable has been a great tool for updating tables seamlessly. One challenge I'm facing is the need to edit a field in my object model that is stored in bits per second. I want to make it easier for the user by automatically con ...

Trigger a scope update externally, without relying on a controller

Having an issue with a jQuery UI select list in an AngularJS app. When an item is selected, the change doesn't register in Angular, unlike a regular select list. Is there a way to make them work together harmoniously? Example: HTML: <div data-ng ...

summoning the iframe from a separate window

In my current setup, I have a link that passes a source to an iframe: <a href='new.mp4' target='showVideo'></a> <iframe src='sample.jpg' name='showVideo' ></iframe> However, what I would lik ...

Issue with specific selectors causing React CSS module malfunction

Currently, I am a beginner in learning React and have been experimenting with CSS modules. Even though Menu.module.css is mostly functioning correctly, it seems to be having an issue applying styles to the .menu a.last selector for some reason (although i ...

Is it advisable to initiate an AJAX call and allow the browser to cancel the request if needed?

When an AJAX request is made, it typically appears in the network tab in Chrome. However, if a client-based redirect occurs at the same time, the AJAX request may be cancelled. But does this mean that the request still reaches the server and executes as ...

Function modifies global variable

What could be causing the global variable to change when using the function write_ACK_ONLY()? I'm passing the array rxUartBuffer to write_ACK_ONLY() as data = new Array(20), but upon checking the Log Output, it seems that the function is also modifyin ...

Splitting the identifier and the name into individual keys within a JSON object

I've got worker data stored in my database in JSON format, looking like this: {"45051-Cortador 1 Siloc": "hsgvs", "45063-Nihil impedit quia": "okbbd",} Each JSON Key contains an id and the name of the user. For ...

"Encountered a problem while setting up the Mailgun webhook to handle both multipart and URL encoded

I have been working on creating a web hook listener for Mailgun, and I encountered an issue when I realized that Mailgun can post webhooks using either multipart or x-www-form-urlencoded content-types. Currently, my code uses Multer to handle multipart b ...

One div takes a backseat to the other div

I recently delved into learning Bootstrap, but I'm baffled as to why one div is appearing behind another. <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Fa ...

Customizing the DatePicker with a unique button in material-ui

For my current project, I am utilizing a Datepicker component. I am looking to incorporate a custom information button in the upper right corner of the calendar layout, similar to the example image provided below: https://i.stack.imgur.com/fHMbn.png Unfo ...

The Bootstrap alert refuses to close when the close button is clicked

I'm attempting to utilize a Bootstrap alert for displaying a warning. The alert automatically fades and dismisses after a period of time, but I want to provide the user with the option to manually close it. I've included jQuery and js/bootstrap.m ...

Customize the default styles for Angular 2/4 Material's "md-menu" component

Seeking to customize default styles of md-menu in Angular Material. The challenge lies in the dynamic generation of elements by Angular Material, preventing direct access from HTML. Visual representation of DOM: https://i.sstatic.net/v8GE0.png Component ...