Issue with Component: Data is not being injected into controller from ui-router resolve, resulting in undefined data

Encountering an issue with resolve when using a component and ui-router: the data returned after resolving the promise is displaying as "undefined" in the controller.

Service:

class userService {
  constructor ($http, ConfigService, authService) {
    this.$http = $http;
    this.API_URL = `${ConfigService.apiBase}`;
    this.authService = authService;
  }


testAuth () {
    return this.$http.get(this.API_URL + '/test-auth')
 }

getCollaborators () {
    return this.$http.get(this.API_URL + '/collaboratores').then( 
          (resolve) => {   // promise resolve
          console.log('Success',resolve.data);
     }
   )
 }

getAccount () {
   var config = {
   headers: { "X-Shark-CollaboratoreId" : "1"}
  };
  return this.$http.get(this.API_URL + '/accounts' + '/' + 1,     config).then( 
          (resolve) => {   // promise resolve
              console.log('Success',resolve.data);
      }
   )
 }

Module/Component/Routing:

.config(($stateProvider, $urlRouterProvider) => {
 "ngInject";

 $urlRouterProvider.otherwise('/');

 $stateProvider
   .state('core', {
      redirectTo: 'dashboard',
      url: '/core',
      component: 'core',
      resolve: {
        userdata: (userService) => {
            return userService.getCollaborators();
        },
        accdata: (userService) => {
            return userService.getAccount();
        }
      }

    });
})

Controller:

let self;

class CoreController {
  constructor($state,userService,authService,userdata,accdata) {
    this.name = 'core';
    this.$state = $state;
    this.userService = userService;
    this.authService = authService;
    this.userdata = userdata;
    this.accdata = accdata;
    console.log('name',this.name);
    self = this;
    console.log('userdata',self);
  }
}

CoreController.$inject = ['$state','userService',     'authService','userdata','accdata'];

export default CoreController;

Upon injecting the resolved object into the controller after making the http call,

 this.userdata = userdata;
 this.accdata = accdata;

The data shows up as undefined!!! Where could the bug be? Appreciate any help...

Answer №1

Update the getCollaborators function to the following:

getCollaborators () {
  return this.$http.get(this.API_URL + '/collaborators').then( 
      (resolve) => {   // promise resolve
      console.log('Data Retrieved Successfully',resolve.data);
      return resolve;
   });
}

Apply the same modification to the getAccount method as well (i.e., within the success callback, return resolve).

This adjustment will resolve your issue.

The problem was caused by not returning anything in the success callback of the service. When chaining success callbacks, the first callback must return a value that can be used as an argument for the second callback. As the original callback was not returning anything, the resolved value was not accessible in the controller.

Answer №2

Which version of AngularJS are you currently using?

Keep in mind that in version 1.6, a then callback will now receive four parameters: data, status, headers, config, and statusText.

In this particular situation, accessing resolve.data may potentially result in an undefined value.

For further information, please refer to the documentation at: https://docs.angularjs.org/api/ng/service/$http

Answer №3

It appears that your connection is with a component in the state rather than a controller, so the best approach would be to create a component and bind the resolved values to it.

angular
    .module('app')
    .component('main', {
        templateUrl: 'app/main.html',
        controller: MainController,
        controllerAs: 'vm',
        bindings: {
          userdata: '<',
          accdata: '<'
        }
    });

To access the resolved data in your component controller, follow these steps:

const vm = this;
vm.$onInit = () => {
    console.log('userdata: ', vm.userdata);
    console.log('accdata: ', vm.accdata);
}

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

Checking CORS permissions with a pre-flight OPTIONS request

During development, I implement a middleware called cors using the following syntax: app.use(cors({origin: 'http://localhost:8100'})); However, I have noticed that for every route request, two requests are being made as shown in the image below ...

Is there a way in AngularJS to trigger an event at a designated time?

I recently developed a webpage using AngularJS. I am looking to trigger certain actions on my webpage within a specified timeframe. For instance, If it is 2016-01-07 11:00:00, I want ng-show to execute some action. I am utilizing the Angular-timer for ...

Icon bar struggling to contain voluminous material card content

I've incorporated Material UI cards into my project and have an icon bar at the bottom of each card. However, the media within the card is overflowing onto the icon bar, causing a layout issue as illustrated in this screenshot: Below is the code snip ...

Looking to fill every space? Try using React with MUI Grid!

I am currently using Material UI Grid to create an image grid, and I am facing challenges in eliminating the gaps between certain grid items. Despite attempting to modify the alignitems and justify values of the container, I have not been successful in r ...

Advantages of using individual CSS files for components in React.js

As someone diving into the world of Web Development, I am currently honing my skills in React.js. I have grasped the concept of creating Components in React and applying styles to them. I'm curious, would separating CSS files for each React Component ...

Delivering resources through the Nuxt configuration file

https://i.stack.imgur.com/2OWdE.png I came across a bootstrap template online that I want to customize for my Nuxt project. I have stored all the bootstrap files in the static folder. Within the nuxt.config.js file: module.exports = { /* ** Headers ...

Exploring the Interaction of Users with HTML Table Cell <td>

I am currently analyzing the code for a web page. Within this code, users have the ability to double-click on a cell in a table (<td> as shown below) and input a value. Is there a specific attribute or element within this HTML that indicates user in ...

What is the correct method for service injection in Angular 8?

I have encountered an issue while trying to inject a service into my main "App" component. The error message is shown in the screenshot below: constructor(private newsApi: NewsApiService) {} Upon importing the service using the code above, I received the ...

Retrieving JSON data and showcasing it in HTML components

I'm attempting to retrieve JSON responses and showcase them within my predetermined HTML elements. I'm utilizing graphql from datocms. The API explorer displays the following for my model: query MyQuery { allNews { id newsTitle new ...

Retrieve the latest information and update the database with just one ajax request

I am attempting to update a row in the database and retrieve the updated row one at a time using an AJAX call. JavaScript inside the ready function $("button[name='teacher_lock_exam']").on(ace.click_event, function () { var current_exams_id ...

Creating dynamic components in ReactJS allows for versatile and customizable user interfaces. By passing

Within the DataGridCell component, I am trying to implement a feature that allows me to specify which component should be used to render the content of the cell. Additionally, I need to pass props into this component. Below is my simplified attempt at achi ...

What could be causing the unexpected behavior of req.query in NEXT.js?

In the latest version of NextJS App Router, I have the following code located in the file app\api\products\route.tsx import { initMongoose } from "@/lib/mongoose"; import Product from "@/models/products"; import { NextApi ...

Packager freezing after running npm audit and the component directory is nonfunctional

Greetings, To begin with, I would like to acknowledge that this issue may have been addressed in previous posts, but despite following suggestions on Stack Overflow and GitHub, I am still facing two specific problems. Here are the issues I am encounterin ...

There seems to be an issue with the $scope value not being properly updated

In my AngularJS application, I am trying to update a $scope variable and display it in a Bootstrap modal. However, the new value is not appearing in the modal. Here is my code: View: <li ng-controller="QuickViewController"> <a href="javascri ...

Creating an Interactive Menu System with Nested Options in Angular 2

I have a JSON structure that I need to transform into a menu with sub-menus based on the value of the sub-menu_location field. Here's an example: { "data": [ { "menu_name": "Primary Operations", "enabled": true, "sub-menu_lo ...

Passing a JSON object between pages in Next.js using props during programmatic navigation

In my Next.js project, I have two pages. On the first page, the user fills out a form to create a post. The information is stored in a large JSON object, which needs to be passed to the second page for the user to preview the post before finalizing it. Wi ...

Two components, one scroll bar, both moving within the same plane

For those interested, here is the JSFiddle link for further exploration: https://jsfiddle.net/q6q499ew/ Currently, there is a basic functionality in place where when you scroll past a certain point, an element becomes stuck until you start scrolling back ...

Is the Webpack vendors JS bundle in Vue CLI containing unlisted code that is not in the dependencies or package-lock.json file?

An information security auditing tool flagged an outdated library with known vulnerabilities in our webpack-bundled chunk-vendors.js file generated using Vue CLI: The library in question is YUI 2.9.0. It appears that this library is not fully included, a ...

What is the process for extracting HTML content using the JavaScript executor?

import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; public class WebDriverExample { public static void main(String[] args) { System.setProperty("webdriver.c ...

Angular2's hidden feature isn't functioning properly

There is a common suggestion to use *ngIf better than [hidden] but in my scenario, I want to keep the element in the DOM without it being visible. In my component.html file, I have: <article #articleId id="bodyArticle" [hidden]="isClicked"></art ...