Win Win - 5 months ago 168
AngularJS Question

How to wait for promise from UI Router Resolve in Angular 1.5 Component

I'm using Angular 1.5 Component. I could not figure out how to get the data via Resolve.

Could you please shed some light?

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

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

<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link data-require="bootstrap-css@3.3.6" 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

You had forgot to return a promise from your promiseFollowers promise.

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

And there after you also need to define a bindings option to retrieve a value passed from resolve

bindings: {
   promiseFollowers: '='
},

Demo Plunkr

Comments