AngularJS route resolve to retrieve $http data using the id parameter

My application has multiple screens and controllers that rely on data from servers. I want to use the router resolve functionality to ensure that all data dependencies are resolved before rendering the screen. However, I am facing an issue with the example provided below. Can you help me understand why it is not working properly?

angular.module('app',['ngRoute'])
    .service('Data1', function ($q, $routeProvider, $http) {
        var self = this;

        this.fetch = function() {return $http.get('/json/data1',{id:$routeProvider.id})}
    }
    .service('Data2', function ($q, $routeProvider, $http) {
        var self = this;
        this.fetch = function() {return $http.get('/json/data2',{id:$routeProvider.id})}
    }
    .config(function($routeProvider){
        §routeProvider.when('/:id',{
            controller:'TestCtrl',
            templateUrl:'template.html',
            resolve: {
                data1: function (Data1) { return Data1.fetch(); },
                data1: function (Data2) { return Data2.fetch(); }
            }

        });
    })
    .controller('TestCtrl', function($location, $routeParams, $http, data1,data2) {
        console.log(data1);
        console.log(data2);
    });

Answer â„–1

Here's a demonstration showcasing the correct usage of resolve with $routeProvider. Firstly, I established two factories similar to the ones you provided. In my configuration settings, I defined a route where I intend to inject data from these factories. I specified the controller and template, but the focus is on the resolve section, where I assigned two functions - someData and someMoreData. Within these functions, I utilized the data1 and data2 factories along with $routeParams to fetch and return the data.

Within the controller definition, I requested injection of $scope and the two resolve properties previously set in $routeProvider.

It's essential to note that if your factories involve API calls for resolving data, the page loading process will pause until this data retrieval is complete. The controller will not initialize until all processes are finished. Consider implementing a loading animation while waiting for the data, which can be achieved with various examples found on StackOverflow.

angular.module('app.factories', [])
  .factory('data1', ['$q', '$timeout', function($q, $timeout) {
    // Factory code for data1 here
  }])
  .factory('data2', ['$q', '$timeout', function($q, $timeout) {
    // Factory code for data2 here
  }]);

angular.module('app', ['ngRoute', 'app.factories'])
  .config(['$routeProvider',
    function($routeProvider) {
      // Route configuration using $routeProvider
    }
  ])
  .controller('defaultCtrl', function() { })
  .controller('testCtrl', ['$scope', 'someData', 'someMoreData',
    function($scope, someData, someMoreData) {
      // Controller logic here
    }
  ]);
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular-route.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>

<body>
  <div ng-view>

  </div>
</body>

</html>

Edit Updated the structure so that factories reside in their own module and are injected as dependencies to the app module for improved architecture (typically each factory should have its own module).

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

Managing timestamps of creation and modification with Sequelize and Postgresql

As a newcomer to Sequelize, I find myself grappling with the intricacies of model timestamps management. Despite prior experience with another ORM in a different language, I'm struggling to wrap my head around how to automatically handle "createdAt" a ...

Exploring the method of extracting multiple checkbox values from an HTML form

While I'm aware that jQuery can be used to retrieve checkbox values when there are multiple checkboxes, the solutions available online don't seem to work for me. This is because my checkbox inputs are embedded within an HTML form, and none of the ...

How a JavaScript function handles the scope of a for loop index

Here's some Javascript code I'm working with: func1() { for(i = 2; i < 5; i ++) { console.log(i); func2(i); } } func2(x) { for(i = 100; i < 200; i ++) { do something } } I've noticed that when runni ...

Creating a Website that Adapts to Different Browser Sizes: Tips and Tricks

I am currently working on a website that features a video background (mp4 file). However, I noticed that the video appears differently in Chrome, Explorer, and Firefox. In order to ensure compatibility across all browsers, I need to make some adjustments i ...

What is the method for configuring environment variables in the Lumber framework?

Installing Lumber CLI npm install -g lumber-cli -s Next, lumber generate "adminpanel_test" --connection-url "mysql://root@localhost:3306/admin-dev" --ssl "false" --application-host "localhost" --application-port "3310" Error: lumber is not recognized a ...

TypeScript is unable to locate the identifier 'async' within the code

While working with TypeScript, I encountered an error: [ts] Cannot find name 'async' Here is the code snippet causing the issue: async someAsyncCode() { let asyncFn = () => { return new Promise((resolve: Function) => { resolv ...

Remove the final 5 characters from the HTML text

Below is the code block that I am unable to modify: <div class="parent"> <div class="wrap"> <span class="content">2026-01-31-08:00</span> </div> <div class="wrap" ...

What are the best methods for querying and updating a self-relation in Prisma?

I recently obtained some self-relation tables directly from a specific Prisma example. model User { id Int @id @default(autoincrement()) name String? followedBy Follows[] @relation("follower") following Follows[] @rel ...

What is the process for obtaining a compilation of JavaScript files that are run when an event is triggered?

How can I generate a list of all the JavaScript files that are triggered when a button is clicked or an input field is selected in a complex system? Is it possible to achieve this with Chrome DevTools, or are there alternative solutions available? If Chro ...

Locate the index of an item within an array of objects based on a matching property in the

My current situation involves having an array of objects structured like this : [ {label: "<p>Opacity | %<br/></p>", customRow: false, id: 0, items: Array(13)}, {label: "Brand_hs_id", customRow: false, id: 0, items: A ...

Testing uuid in jest - simulating uuid usage within a service method

I'm struggling with mocking uuid in a jest test where the real function is being called to compare the result with an expected value. The service function relies on uuid, but all my attempts at mocking it have failed. Here's a snippet of my code ...

The CSS class is not properly implemented in the React component

I value your time and assistance. I have spent many hours trying to solve this issue but seem unable to reach a resolution. Here is the React component in question: import styles from './style.scss'; class ButtonComponent extends React.Compone ...

assigning the browser's width to a variable within an scss file

Is there a way to dynamically set the browser's width as a variable? I am familiar with @media queries, but I need to calculate the browser's width for a specific purpose. I attempted using jQuery to achieve this, and it works well with a fixed ...

What could be the reason for my ajax request coming back with no data?

When I make this ajax request: $.ajax({ type: "POST", url: "/admin/RoutingIndicators/Add", data: { newSecondaryRI: newRi }, success: function () { alert('hit'); document.location.reload(true); }, error: fu ...

Using ng-class directive with condition in AngularJS

Here is a unique pop-up that allows users to encode item information. https://i.sstatic.net/sn9QZ.png I need to implement a feature where, if both the Foreign Currency and Conversion Rate fields have values, the Amount should be calculated by multiplying ...

The functionality of sorting or searching in jqGrid does not support columns that utilize json dot notation

Here is the jqGrid code snippet that I am working with: $("#report").jqGrid( { url: '/py/db?coll=report', datatype: 'json', height: 250, colNames: ['ACN', 'Status', &ap ...

Support for Ajax requests on Android devices

Can Android 4.0+ support Ajax Requests? If so, please offer some guidance. I am looking to make Ajax calls from an Android WebView using JavaScript. ...

The promise was formed in a handler and left unfulfilled in Bluebird

Initially, I understand the need to return promises in order to prevent the warning. I have attempted returning null as suggested in the documentation here. Take a look at this code snippet which is used within Mongoose's pre-save hook, though the war ...

What are the best ways to handle processing of incorrect input?

I created a custom validator to prevent the form from being submitted with invalid data, and as an added bonus, I noticed that the input is not processed when it's invalid - for example, ng-change isn't triggered even though the input is changing ...

Error message: The Vue component is unable to assign a value to the 'render' property of an undefined object

The console is displaying an error message that reads: Uncaught TypeError: Cannot set property 'render' of undefined at normalizeComponent (componentNormalizer.js?2877:24)... This error is preventing my view from rendering and seems to be t ...