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

How can I make the row color of a jQuery datatable change when the row is selected?

One of my challenges involves implementing a jquery dataTable (view here) where each row contains a checkbox. I want the row's color to change when the checkbox is checked. This is the approach I attempted: <table id="tabellaOrdinaFarmaci" class=" ...

How can one break down enum values in typescript?

I've defined an enum in TypeScript as shown below: export enum XMPPElementName { state = "state", presence = "presence", iq = "iq", unreadCount = "uc", otherUserUnreadCount = "ouc", sequenc ...

JS Unable to get scrollIntoView function to work with mousewheel event

I have been working with the script provided above. It correctly displays the id in the browser console, but unfortunately, it is not triggering the scrolling function as expected. var divID = null; var up = null; var down = null; function div(x) { s ...

Angular findIndex troubleshooting: solutions and tips

INFORMATION = { code: 'no1', name: 'Room 1', room: { id: 'num1', class: 'school 1' } }; DATABASE = [{ code: 'no1', name: 'Room 1', room: { id: 'num1', ...

Utilizing JavaScript to pass parameters to an IFRAME within Dynamics CRM

While trying to access http://localhost:80/testsite in an IFRAME, everything seems to work perfectly. However, once I attempt to pass field values as parameters, nothing happens. Oddly enough, accessing the page directly from a browser with parameters work ...

Puppeteer has a limit of running only three instances on Heroku

Currently, I am in the process of developing a website that employs puppeteer to extract information from another site. The npm server works flawlessly on my local machine, but once deployed on Heroku, it halts after processing the first three files. The ...

Enable the x-axis months to be interactive in a chart.js line graph

Currently, I am in the process of developing a line chart using chart.js. The x-axis of the chart is time-based and represents months. I want to make each "month column" clickable/selectable, but I'm facing difficulty in achieving this functionality ...

Accessing stored web pages / Browser as an interactive interface

I have a couple of questions I need help with. The first one is about how to open a saved HTML file in a browser without an internet connection. Next, I'm looking for advice on using the browser as a user interface for a desktop image viewing program ...

Add the content of a JavaScript variable to a label without using any scripting

Is there a way to concatenate the value of a JavaScript variable with a label without utilizing jQuery? For example: Var global_message = "1234"; <label id="my-label">Test</label> I desire the concatenated value "Test1234" to be displayed o ...

Struggling to access YouTube account via Google sign-in using Puppeteer framework

I am facing an issue with my puppeteer code where I am unable to proceed past the email page after clicking next due to some bot protection by Google advising me to "Try using a different browser...etc". Is there a way to bypass this using puppeteer? I h ...

Utilize ramda.js to pair an identifier key with values from a nested array of objects

I am currently working on a task that involves manipulating an array of nested objects and arrays to calculate a total score for each identifier and store it in a new object. The JSON data I have is structured as follows: { "AllData" : [ { "c ...

Despite being installed, the message 'concurrently: command not found' pops up

I'm attempting to run two scripts simultaneously, and I came across the concurrently package that is supposed to assist with this. After executing npm install concurrently --save and verifying it in my package.json, I faced an issue when trying to run ...

The issue of asynchronous behavior causing malfunctioning of the PayPal button

import { PayPalButton } from 'react-paypal-button-v2' <PayPalButton amount={total} onSuccess={tranSuccess} /> const tranSuccess = async(payment) => { c ...

How to display an element using an if statement in Next.js

I am attempting to incorporate a parameter into a nextJS component that will only display if a certain condition is met. At the moment, my code looks like this: return ( <div role="main" aria-label={this.props.title} classN ...

Unable to access property 'scrollToBottom' as it is undefined

I'm encountering the error "Cannot read property 'scrollToBottom' of undefined" and haven't been able to find a solution anywhere, hence this post: Here is my use case: I have a custom accordion list, and on click of one of the list i ...

Positioning Backgrounds with Padding in DIV Elements

I am trying to figure out how to add a check mark next to text in a button with specific styling. I have managed to get the check mark aligned properly using Background:left center, but I also want to add padding and adjust spacing. Is there a way to achie ...

Increased/Decreased impact

Can someone explain how the "Tell me more" effect is achieved on the website linked below? I'm familiar with the read more/less effect in jQuery, but what intrigues me is that the page cannot be scrolled unless the button is clicked. Here is the link ...

Display div - conceal div - pause for 15 minutes - continue the cycle

I have a challenging JavaScript task that I've been struggling with for quite some time. The goal is to display a div for 5 seconds, hide it, wait for 15 minutes, then show it again for another 5 seconds, and continue this process in an infinite loop. ...

Typescript: The type 'X' does not correspond with the signature '(prevState: undefined): undefined' in any way

My React Native app, which is written in TypeScript, has been giving me a hard time with an error lately. The issue revolves around a Searchable List feature. This list starts off with an Array of values and gets updated when users type into a search bar. ...

Obtaining the blog slug dynamically upon clicking with ReactJS

Currently, I am developing a project using Reactjs and Nextjs. One of the tasks at hand is to obtain the "slug" value after clicking on a blog post. However, at this moment, the value returned is undefined despite trying the following code: <h4 onClic ...