Troubleshoot the issue of the service function not being triggered

Seeking help with my Angular project as I am facing an issue with resolve and $resource. Despite spending a whole day on it, I couldn't find a solution. When using resolve to fetch data with $resource and ui-router, the service method never gets called even though the state loads fine. The state includes a ui-grid which appears empty. The project currently utilizes a json-server for data, but no http request is shown on the server. Below is some relevant code:

angular.module('carsApp', ['ui.router', 'ngResource', 'ui.bootstrap', 'ui.grid'])
  .config(function($stateProvider, $urlRouterProvider) {
    $stateProvider
      .state('app.main.car', {
        url: "",
        abstract: true,
        views: {
          'grid': {
            templateUrl: 'views/crid.html',
            controller: 'GridController'
          },
          'cars': {
            templateUrl: 'views/cars.html',
            controller: 'CarController'

          }
        },
        resolve: {
          cars: ['gridFactory', function(gridFactory) {
            return gridFactory.getCars();
          }],
          dealer: function() {
            return {};
          }
        }
      })

      .state('app.main.car.all', {
        url: "car/summary",
        views: {
          'summary': {
            templateUrl: 'views/summary.html'

          }
        },
        resolve: {
          cars: ['gridFactory', function(gridFactory) {
            return gridFactory.getCars();
          }],
          dealer: function() {
            return {};
          }
        }
      });

    $urlRouterProvider.otherwise('/');
  });

Service:

.service('gridFactory', ['$resource', 'baseURL', function($resource, baseURL) {

        this.getCars = function() {
          return $resource(baseURL + "cars", null, {
            'query': {
              method: 'GET',
              isArray: true,
            }
          });
        }


      }

Controller:

.controller('GridController', ['$scope', '$stateParams', '$state', 'gridFactory', 'cars', 'dealer', function($scope, $stateParams, $state, gridFactory, cars, dealer) {

        $scope.cars = cars;
        $scope.dealer = dealer;

        console.log('scope objects ' + JSON.stringify($scope.cars));

      }

Would appreciate any insights into what I might be missing. Thank you for your time!

Answer №1

To retrieve data, it is necessary to utilize the query() method and return the promise from the $resource. By default, $resource methods return an empty object or array that is filled in once the request is complete

resolve: {          
      cars: ['gridFactory', function(gridFactory) {
        // Make a Service call that returns a Promise
        return gridFactory.getCars().query().$promise;
      }],
      dealer: ....

Alternatively, some of this functionality can be abstracted into the service method, allowing it to return the query().$promise

DEMO

Answer №2

It appears that there may be a problem with the get cars method in your factory:

Here is a potential solution:

 .service('gridFactory', ['$resource', 'baseURL', function($resource, baseURL) {

    this.getCars = function() {
      var cars =  $resource(baseURL + "cars", null, {
        'query': {
          method: 'GET',
          isArray: true,
          // including an authorization header here to use this version of query

        }

       return new Promise(function(resolve, reject){

          var result = [];

          cars.query(function (response) {
             angular.forEach(response, function (item) {
               result.push(item);
             }
          }

          resolve(result);

        })

       })

      });
    }


  }

You may find this question on Stack Overflow helpful in addressing your issue

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

Is there a way to emulate synchronous behavior in JavaScript?

var routeSearch = new MyGlobal.findRoutes({ originPlaceId: search.placeInputIds.originPlaceId, destinationPlaceId: search.placeInputIds.destinationPlaceId, directionsService: search.directionsService, directionsDisplay: sear ...

Issue with an external library in Angular 2

After generating my Angular 2 library using the yeoman generator and adding it to my main Angular project, I encountered errors when running the app in production mode. The specific errors include: WARNING in ./src/$$_gendir/app/services/main/main.compone ...

Ways to efficiently group and aggregate data in JavaScript, inspired by LINQ techniques

I'm feeling overwhelmed by this. Could you lend a hand? Consider the following .NET classes: Teacher: public class Teacher { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } publ ...

I must align a bootstrap modal(dialog) based on the opener's position

Using a bootstrap modal for the settings dialog in an angularJS app, but facing an issue where it opens in the center of the page by default instead of relative to the opener. Looking for a solution to keep it positioned correctly when scrolling. Code: M ...

React Alert Remove Alert: Each item in a list must be assigned a distinct "identifier" prop

How can I resolve the React warning about needing a unique "key" prop for each child in a list? I'm trying to eliminate the warning that says: "Each child in a list should have a unique key prop." The code snippet causing this warning is shown below ...

Switching from the global import module pattern to ES6 modules

In recent years, my approach to JavaScript development has involved using the global import method. Typically, I work with a set of utility functions packaged and passed to a separate site module containing individual functions for each web functionality: ...

Darkness prevails even in the presence of light

I'm currently in the process of developing a game engine using ThreeJS, and I have encountered an issue with lighting that I need assistance with. My project involves creating a grid-based RPG where each cell consists of a 10 x 10 floor and possibly ...

What is the best way to dynamically adjust the top CSS of an element when it is positioned at the top or

Is there a way to dynamically set the top CSS when an element is over the top or bottom of a page? First, hover over the first cat image. It's working fine. http://image.ohozaa.com/i/480/7YpWei.jpg When I scroll the page to the bottom and hover ove ...

Issue: Proper handling of data serialization from getStaticProps in Next.js

I've been working on Next.js and encountered an issue while trying to access data. Error: Error serializing `.profileData` returned from `getStaticProps` in "/profile/[slug]". Reason: `undefined` cannot be serialized as JSON. Please use `nul ...

Encountering a problem while trying to pin a message on Discord

Whenever a message is pinned in discord, it causes the bot to crash with the following error (although it can recover with forever but that's beside the point). The pinned message can be of any type (regular or embed). if (!value) throw new RangeE ...

Avoiding the occurrence of moiré patterns when using pixi.js

My goal is to create a zoomable canvas with rectangles arranged in a grid using pixi.js. Despite everything working smoothly, I'm facing heavy moire effects due to the grid. My understanding of pixi.js and webgl is limited, but I suspect that the anti ...

Tips for creating a simulated asynchronous queue with blocking functionality in JavaScript or TypeScript

How about this for a paradox: I'm looking to develop an asynchronous blocking queue in JavaScript/TypeScript (or any other language if Typescript is not feasible). Essentially, I want to create something similar to Java's BlockingQueue, but inste ...

A sophisticated approach to implementing a search functionality within a complex JSON structure containing nested arrays using JavaScript

Searching for data in JSON format: { "results": { "key1": [ { "step": "step1", "result": "pass" } , { "step": "step2", "result": "pending" } ...

Preventing the form from being enabled by default when using 'ng-model'

I have an input field labeled name. I have set a default value of 'Enter your Name' using the ng-model, but this causes the form submit button to become enabled. How can I prevent the submit button from being enabled by the default value? Here i ...

The javascript function ceases to operate once the div is refreshed

$(function() { $(".reqdeb").click(function() { console.log("Functioning properly"); var req_id = $(this).attr("id"); var info = 'id=' + req_id; if (confirm("Confirm deletion of request?")) { $.ajax({ cache : false, ...

Steps for relocating Express server (using MERN stack) to a subdirectory and functioning on Heroku

In my MERN stack project, I recently had to reorganize the server-related files into their own subdirectory due to issues with ESLINT, VSCODE, and package.json configurations that were causing errors. However, after making this change, Heroku started thro ...

Angucomplete-alt fails to display dropdown menu

On my website, there is a textarea where users need to input the name of a group project. The goal is to implement autocomplete functionality, so as users type in the project name, a dropdown menu will appear with suggestions of existing projects to assist ...

Transferring pictures between folders

I am currently developing an Angular app that involves working with two images: X.png and Y.png. My goal is to copy these images from the assets folder to a specific location on the C drive (c:\users\images) whose path is received as a variable. ...

elements that are left between two URLs

I recently started learning Angular and I'm working on creating a website where certain elements persist between different URLs. I'm not sure of the best approach to achieve this. Ideally, the clicked elements should be present in both URLs (part ...

What steps should I take to ensure my .js.erb files are compatible with Rails 7?

I have been following a Rails Tutorial on Building a Link Shortener with Rails 6 and Ruby 2.xx to create an app. However, I am using Rails 7.0.4 and Ruby 3.0.0. I encountered an issue with my create.js.erb file not functioning properly. After some research ...