Guide on waiting for promise from UI Router Resolve within an Angular 1.5 Component

Help needed with Angular 1.5 Component and Resolve for data retrieval

Seeking guidance on utilizing Resolve to fetch data.

Plunker: https://plnkr.co/edit/2wv4YWn8YQvow6FDcGV0

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <link data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e7858888939493958697ca849494a7d4c9d4c9d1">[email protected]</a>" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
    <script>document.write('<base href="' + document.location + '" />');</script>
    <script src="https://code.angularjs.org/1.5.7/angular.js"></script>
    <script src="https://code.angularjs.org/1.5.7/angular-route.js"></script>
    <script src="app.js"></script>
  </head>

  <body>
    <ng-view></ng-view>
  </body>

</html>

app.js

(function () {

    angular
      .module("app", ['ngRoute'])
      .config(function($routeProvider){
        $routeProvider
          .when("/home", {
              template: `<main 
                promise-followers="$resolve.promiseFollowers"></main>`,
              resolve: {promiseFollowers: function ($http) {
                    $http.get("https://api.github.com/users/octocat/followers")
                      .then(function(result) { 
                        return result.data;
                      }, function(result) { 
                        console.log(result);
                      });
                }
              },
          })
          .otherwise({ redirectTo: "/home" } );
      })
      .component("main", {
        template: `<h3>Demo Angular 1.5 Resolver</h3>
        <p>Promise Data from Controller : 
          <select ng-model="$ctrl.selected" 
            ng-options="option.id as option.login for option in $ctrl.followers"></select>
        </p>

        <p>Promise Data from Resolve : 
          <select ng-model="$ctrl.selected" 
            ng-options="option.id as option.login for option in $ctrl.promiseFollowers"></select>
          <span class="label label-danger">Not Working</span>
        </p>        

        <h4>Regular Selector Selected: {{$ctrl.selected}}</h4>`, 

        controller: function($http){

          var self = this;

          // This is just testing to to make sure api is working.
          $http.get("https://api.github.com/users/octocat/followers")
            .then(function(result) { 
              self.followers = result.data;
            }, function(result) { 
              console.log(result);
            });

          self.$onInit = function () {
            console.log(self.promiseFollowers);
          }    
        }
      });

})();

Answer №1

Don't forget to make sure you return a promise from your promiseFollowers function.

promiseFollowers: function ($http) {
     return $http.get(...){
     }
}

Also, remember to add a bindings option to receive a value passed from resolve

bindings: {
   promiseFollowers: '='
},

Check out the demo on Plunkr

Answer №2

For more information, you can check out this helpful link: .

In summary, the key is to "Inject resolve to the controller" in order to resolve 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

Expanding the capabilities of jQuery UI event handling

I am looking for a way to enhance dialog functionality by automatically destroying it when closed, without the need to add additional code to each dialog call in my current project. My idea is to override the default dialog close event. After researching ...

Error occurs when attempting to clear the cache storage

useEffect(async () => { caches.open('my-cache') }, [token, user_id]) Upon trying to log out of the application, const logoutFunc = () => { localStorage.clear() caches.keys().then((list) => list.map((key) => { ...

The addEventListener function seems to encounter issues in IE11

There is a javascript function below that uploads the selected file and updates the grid. It works perfectly in Firefox, but there seems to be an issue with IE11. The "ESignature/Registration" function within the addEventListener does not seem to execute ...

Tips on customizing the appearance of React rendering components

<div> <h3>{this.props.product.name}</h3> <h3>{this.props.product.code}</h3> {this.renderColors()} <article> <div da ...

Determine the mean value from an array of JSON objects in an asynchronous manner

Can you help me calculate the average pressure for each device ID in this JSON data set? [ { "deviceId": 121, "Pressure": 120 }, { "deviceId": 121, "Pressure": 80 }, { "deviceId": 130, "P ...

What is the best way to incorporate various layouts into an Angular JS project effortlessly?

Is there a way to specify unique layouts for various routes? Ideally, I would like to define layouts and other parameters within an object in the route configuration and have them automatically apply when the route changes. ...

Creating a React.js NavBar: Can we refer to another component's HTML code? (Exploring the idea of a navigation bar that links to components within the same route)

My goal is to create a navbar for my personal website application that references different content sections (such as About, Skills, etc.) all on a single page route. However, I am running into some challenges. I can easily reference markup with ids/classe ...

Background image specifically for the Fullcalendar sun component

When setting a background image for Sunday in the month view, I noticed that the day "Sunday" in the header is also getting the same background. The CSS for the table thread has classes like .fc-sun and .fc-mon set as well, but I'm not sure how to rem ...

Exporting Datatable to Excel may cause line breaks

I have structured my project in the following manner: https://jsfiddle.net/Eufragio/u342qgoz/1/ When I export to excel, I require a better layout or a more visible method to display my results $(document).ready( function () { var table = $('#exam ...

InvalidAction: The function forEach cannot be applied to "res"

Here is the HTML code that I am currently working with: <div *ngIf="chart" class="col-xl-4 col-lg-6"> <div class="card cardColor mb-3"> <div class="card-header headColor"> <img class="img-fluid" src="../../../ ...

Splitting a string in Typescript based on regex group that identifies digits from the end

Looking to separate a string in a specific format - text = "a bunch of words 22 minutes ago some additional text". Only interested in the portion before the digits, like "a bunch of words". The string may contain 'minute', & ...

Guide to utilizing $refs effectively in Vue.js templates

Is there a way to display the input value automatically without using v-model and by making use of the "ref" attribute? <div class="form-group m-b-40"> <input type="text" class="form-control" id="name" ref="name" required> </div> {{sh ...

Contrast between v-for arrangements

Would anyone be able to clarify the distinction between these two v-for structures? <li v-for="item in items" :key="item"> </li> and <li v-for="(item, i) in items" :key="i"> </li> ...

Using the Vuex getter to populate a component with data using the v-for directive

I am currently constructing a vue2 component, utilizing a vuex store object. The structure of the component is as follows: <template> <ul id="display"> <li v-for="item in sourceData()"> {{item.id}} </li ...

Angular - Invoking a different component's method to switch the visibility of a div

I currently have two components - one serving as my header and the other consisting of plain text. The header contains a menu with various options. My goal is to toggle a boolean in the second component and display the complete HTML when an option in the ...

Transform a 2-dimensional array of numbers into an array of objects labeled with a "row" index

Today my brain seems to be in full-on "fart" mode. Struggling to find a clean solution for this task without resorting to an ugly loop or recursion. I have a 2D array of numbers that looks like this: const layoutMatrix = [ 1, [1], [0.5, 0.5], [0.2 ...

Surprising non-synchronous operation within the computed property "vue/no-async-in-computed-properties" in Vue3

I am currently working on a Vue3 project and encountering an error when running it. Below is the complete code snippet that I am using. Can anyone assist me in resolving this issue? Thank you in advance. <script> import axios from 'axios'; ...

Providing data from a javascript xml file upon page initialization

I am aiming to extract multiple values from an XML file as soon as an HTML page is loaded. The XML file remains constant and will not change over time. It will be stored in the same directory as the HTML page. The purpose of this XML file is to fill severa ...

Is there a method in Discord.JS to remove an embed from a message sent by a user?

Currently, I am developing a bot utilizing the Discord.JS API. This bot is designed to stream audio from specific YouTube links using ytdl-core. Whenever a link is typed in, an embed of the YouTube video appears. While there are methods to disable embeds o ...

methods for retrieving nested JSON data from an API endpoint

My data has been exported in JSON format { "count":79, "stories":{ "23658975":{ "title":"NOMINATIVO", "description":"BUSDRAGHI PIERGIORGIO", "updated_at":"2013-06-16T18:55:56+02:00", "created_at":"2013-06-16T18:39:06+02:00", "du ...