Struggling with grasping the concept of passing MongoDB data between states in Angular UI-Router? Let us lend

Currently, I am facing an issue with passing mongodb data from one state to another using ui-router in my app. The goal is to create a platform where users can view each other's profiles by clicking on them. Although I have successfully retrieved the list of user profiles, when clicked, the individual profile data does not load, resulting in a blank profile.

In my app.js file:

angular.module('MyApp', ['ui.router']).config(function($stateProvider, $urlRouterProvider, $authProvider) {
  $stateProvider
    .state('home', {
        url: '/',
        controller: 'HomeCtrl',
        templateUrl: 'partials/home.html'
    })
    // Other states defined here...

Within account.js:

angular.module('MyApp').factory('Account', function($http, $stateParams) {
  return {
      getProfile: function() {
          return $http.get('/api/me/:id');
      },
      // Further functions defined here...
  };

In match.list.html:

<div ng-repeat="user in users">
    <div class="col-xs-12 col-sm-6 col-md-6">
        <div class="well well-sm">
            <div class="row">
                <h1>{{user.displayName}}</h1>
                <a ng-href="#/match/{{user.displayName}}">See {{user.displayName}}!</a>
            </div>
        </div>
    </div>
</div>

The above part works as expected, displaying the list of users. However, the issue arises in match.profile.html when clicking on a user's profile:

<h1>{{user.displayName}}</h1>
<h1>{{user.age}}</h1>
etc...

I suspect that the problem lies within the controller setup in match.js:

angular.module('MyApp')
.controller('matchCtrl', function($scope, toastr, Account) {
   // Controller functionality here...
});

The REST API endpoint used in Node.js for retrieving user data:

app.get('/api/me/', function(req, res) {
  User.find(function(err, user) {
    res.send(user);
  });
});

// Additional endpoints defined here...

Answer №1

The issue with your match.profile controller is that it is not properly resolving the promise returned from the API call to getUserProfile, resulting in a blank UI.

To fix this, you need to inject the Account service into the controller and ensure that the getUserProfile method is called correctly (using () instead of []).

controller: function($scope, $stateParams, Account) {
  $scope.user = Account.getUserProfile($stateParams.displayName);
}

Additionally, relying on $stateParams within the Account factory may lead to inconsistencies since $stateParams might not update as expected when changing states. Make sure to verify the API endpoint construction using developer tools or logging $stateParams inside the getUserProfile method. It's advisable to pass the URL variable as an argument for better control.

getUserProfile: function(displayName) {
  return $http.get('/api/me' + displayName);
}

Update your controller as follows:

controller: function($scope, $stateParams, Account) {
  Account.getUserProfile($stateParams.displayName)
  .then(function (profile) {
    $scope.user = profile;
  });
}

Tips for Using UI-Router Effectively

  • When working with UI-Router, focus on application states rather than URLs. Use ui-sref instead of ng-href for transitioning between states. Pass state names, not URLs, and provide arguments using $stateParams.

  • Utilize resolve functions in UI-Router to load data before the state renders. This ensures that data is available to the state before rendering the UI.

    .state('match.profile', {
      url: '/:displayName',
      templateUrl: 'partials/match.profile.html',
      resolve: {
        profile: function ($stateParams, Account) {
          return Account.getUserProfile($stateParams.displayName)
          .then(function (profile) {
            return profile;
          });<br>
        }
      },
      controller: function($scope, profile) {
        $scope.user = profile;
      }
    });

By utilizing resolve functions, you separate concerns properly in Angular's MVC architecture, ensuring that controllers are not responsible for loading their own data but can rely on pre-loaded data.

Answer №2

It appears that you are not making the correct method call for getUserProfile. This method is not directly available in the $scope, instead you need to access it through the Account service. Remember, method calls should be enclosed in parentheses () and not in square brackets []. Additionally, data from the getUserProfile method can be retrieved using the .then function.

Code

.state('match.profile', {
    url: '/:displayName',
    templateUrl: 'partials/match.profile.html',
    controller: function($scope, $stateParams, Account) {
        Account.getUserProfile($stateParams.displayName)
        .then(function(res){
           var data = res.data;
           $scope.user = data;
        }, function(error){
           console.log(error);
        });
    }
});

Answer №3

getUserProfile is a method within the Account service that you are utilizing

$scope.getUserProfile[$stateParams.displayName]

To correct this, update it to:

Account.getUserProfile($stateParams.displayName);

The code should resemble something like this:

.state('match.profile', {
    url: '/:displayName',
    templateUrl: 'partials/match.profile.html',
    controller: function($scope, $stateParams, Account) {
        $scope.user = Account.getUserProfile[$stateParams.displayName];
    }
});

You have also overlooked adding a slash in the getUserProfile function:

getUserProfile: function() {
    return $http.get('/api/me' + $stateParams.displayName);
},

This should be updated to:

getUserProfile: function(){
    return $http.get('/api/me/' + $stateParams.displayName).then(function(res){
        return res.data;
    });
}

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

Creating a dynamic table based on selected dropdown option

I need to create a dynamic table of questions depending on the user's selection from a dropdown menu. When the user chooses a category, I want to pass that information to an API using the GET method. My controller is built using AngularJS. However, I ...

Non-sequential parameter order in JavaScript

Below you will find a regular function that includes named parameters: function who(name, age, isMale, weight) { alert(name + ' (' + (isMale ? 'male' : 'female') + '), ' + age + ' years old, ' + weight ...

Generate a unique sequence not functioning

I'm attempting to generate a unique string composed of random characters, similar to the example found at this source. $(document).ready(function(){ $('#randomize').click(function() { var str = ""; var possibleChars = "michaeljo ...

What is the best way to compare a LatLng object with another one that is stored in an array?

Just starting out with JavaScript and decided to work on building apps using Google Maps. However, I've come across a puzzling issue. Take a look at the code snippet below. <html> <head> <script src = "http://maps.googleapis.com/maps/ ...

How to easily toggle all checkboxes within a Vue.js checkbox group

I'm struggling with manipulating an Array of checkboxes that are grouped into parent and child elements. I need to automatically check all child checkboxes when the parent is checked, uncheck them if the parent is unchecked, and update their states in ...

Create the ability to add multiple autocomplete options to a single input field

Currently, I am working on enhancing the autocomplete feature in an input field. My goal is to create a two-stage autocomplete process for each entered item. For example, if someone types "I", the dropdown would display options like IP Address. Upon sele ...

Concentrate on what comes next

Within my JavaScript code, I have the following line: $('input')[$('input').index(this)+9].focus(); I intended for this line to focus on the next element. However, when it executes, I encounter the following error: Error: [$rootSc ...

Assign the default value to the document title

Just a simple question.. If I set an alert to change the document title to "ALERT" temporarily, is there an easy way to change it back afterward? Or will I need to assign an ID to the link tags to reset the title to that ID value? Keep in mind this script ...

Accessing the chosen value of an ng-model

Currently, I'm attempting to refine some search results by utilizing the chosen value from an ng-select element (stripping away unnecessary formatting and details). Here's what I have so far: <select ng-model="medium" ng-options="medium as me ...

I'm having trouble getting the HTML checkbox symbol to show up correctly. My goal is to create all the elements using the DOM

I am currently building all of my elements manually through the DOM tree, and I am attempting to insert a checkbox symbol in this manner: //Add date var tdDate = document.createElement("td"); tdDate.textContent = ("" + workoutList[idx].date); ...

Using external VB script (IE automation) to invoke Java Script on a webpage

On a webpage, there is a functionality where a checkbox can be clicked to select all the checkboxes below it. This is accomplished by invoking a JavaScript function on click. However, when attempting to select that checkbox using VBScript with .getElement ...

Installing global confusion with NPM

npm install css-sprite --save npm install css-sprite -g I'm curious about the significance of these two commands. I understand that "-g" makes it global, but why is that important? And what does "--save" do exactly? ...

CSS animations make canvas irrelevant

Currently, I am working on a project to develop an interactive whiteboard application using PHP and jQuery. Generating a deck and implementing a canvas overlay for drawing purposes are tasks that I have managed to accomplish without any issues. As a self-t ...

To utilize a spread argument, it is essential for it to either be in tuple form or be supplied to a rest

I am currently learning TypeScript and working on converting my project to TypeScript. However, I encountered an error while trying to use spread arguments. I have researched this topic, but I am still unsure of the correct usage. Here is my current appro ...

"Unsuccessful jSON request made by Ajax resulting in undefined response

I've implemented an ajax call to fetch data from a json file and display it in an HTML table. Everything was working fine initially, but now it seems to be returning UNDEFINED. Could it be that the data from the json file hasn't finished loading ...

Using JavaScript to validate a contact form

I am encountering an issue with my code and I am unsure of how to resolve it. The validation is functioning correctly, however, there is a problem where if you enter information in the name input field - for example, "dima", and then move to another fiel ...

Tips for preventing "Undefined" errors when retrieving data in Vue

I am currently working on a basic page that displays data fetched from the server. Here is the setup: <p>Customer's name for the order: {{ order.customer.name }}</p> Javascript: export default { data () { return { order: {} } }, ...

Calculate the sum of the outcomes from executing the MongoDB query and store them in an Array

I need assistance with adding the number of results in my query response and storing them in an array. Can someone assist me with this task? Below is the MongoDB query I am currently using: . I have provided an example of the expected result (example wi ...

What is the best method to pass a JavaScript file array to a Node.js server?

Is it possible to transfer data from a Javascript file linked to an HTML page to a Node.js file on a post route without displaying it on the HTML page? If so, what is the best way to accomplish this? ...

Ways to prevent a particular link from functioning in HTML or JavaScript

Hey there, I am currently using a Gchat voice and video chat script. Check out my website if you're interested. The issue I'm facing is that someone logs into my chatroom and uses this flash link to crash other users' browsers. Whenever th ...