如何在 Angular 1.5 组件中等待来自 UI Router Resolve 的承诺
Posted
技术标签:
【中文标题】如何在 Angular 1.5 组件中等待来自 UI Router Resolve 的承诺【英文标题】:How to wait for promise from UI Router Resolve in Angular 1.5 Component 【发布时间】:2016-10-30 23:16:24 【问题描述】:我正在使用 Angular 1.5 组件。我不知道如何通过 Resolve 获取数据。
你能解释一下吗?
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);
);
)();
【问题讨论】:
【参考方案1】:https://***.com/a/18019915/6524138 如果上述解决方案不起作用,请参考这应该会有所帮助。
Jist:“向控制器注入解析”应该可以解决您的问题。
【讨论】:
【参考方案2】:您忘记从您的promiseFollowers
承诺返回承诺。
promiseFollowers: function ($http)
return $http.get(...)
在此之后,您还需要定义一个 bindings
选项来检索从 resolve 传递的值
bindings:
promiseFollowers: '='
,
Demo Plunkr
【讨论】:
以上是关于如何在 Angular 1.5 组件中等待来自 UI Router Resolve 的承诺的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Angular 1.5 中使用 HTML 选择调用父组件
在 Angular 1.5 中,如何从子组件编译父组件的 html?