[英]Angular component based approach and working with resolve in Router
所以我正在使用基於組件的角度方法,假設我有一個名為<home></home>;
指令<home></home>;
import template from './home.html';
import controller from './home.controller.js';
angular.module('myApp')
.directive('home', homeDirective);
let homeDirective = () => {
return {
restrict: 'E',
template,
controller,
controllerAs: 'vm',
bindToController: true
};
};
現在我可以在我的路由中使用組件<home></home>
,如下所示:
angular.module('myApp')
.config(($routeProvider) => {
$routeProvider.when('/', {
template: '<home></home>'
})
})
我真的很喜歡這種方法,但是使用“舊”方法我習慣在routeconfig中使用“resolve”來僅在解析promise時呈現組件:
angular.module('myApp')
.config(($routeProvider) => {
$routeProvider.when('/', {
templateUrl: './home.html',
controller: './home.controller.js',
resolve: {
message: function(messageService){
return messageService.getMessage();
}
})
})
題
如何在角度中使用基於組件的方法的解析? AAJ
有一個封閉的問題: 支持指令的解決方案 。
結論是他們不希望異步加載任意指令,因為它會導致過多的閃爍。
好消息是Angular 2以一種有凝聚力的方式在DI層支持這個(以及更多)並且不會引入大量額外的復雜性。
在Angular 1.x中,您可以將指令歸因於要從中獲取消息的一些信息,並處理控制器中的異步加載。 這樣你就可以展示一些不錯的裝載機屏幕了。
angular.module('myApp')
.config(($routeProvider) => {
$routeProvider.when('/', {
template: '<home my-datasource="feed1"></home>'
}).when('/other', {
template: '<home my-datasource="feed2"></home>'
})
})
.factory('DataSources', (messageService) => {
return {
feed1: messageService.getMessage,
feed2: messageService.getError
};
});
或者,如果您希望message
始終來自同一個源,則可以將messageService.getMessage().then(...)
刻錄到控制器中。
如果你不希望指令在promises解決之前完全可見,你可以引入一個最初設置為false的作用域變量,然后在解析時將其設置為true,例如:
app.controller('HomeController', ($scope, messageService) => {
$scope.loaded = false;
messageService.getMessage().then(message => {
...
$scope.loaded = true;
});
...
});
並隱藏指令,直到在根元素處加載ng-if="loaded"
。 是的,用戶代碼太多了,但你至少可以控制一切。
事實證明,角度$ routeProvider將已解析的本地傳遞給$ routeChangeSuccess事件(nextRoute.locals)。 因此,您可以創建一個偵聽路由更改並公開本地的服務:
angular.module('myApp', ['ngRoute'])
.factory('$routeLocals', function($rootScope) {
var locals = {};
$rootScope.$on('$routeChangeSuccess', function(_, newRoute) {
angular.copy(newRoute.locals, locals);
});
return locals;
})
.run(function($routeLocals) {});
然后你可以將$ routeLocals注入你的指令並使用它們。
示例: http : //codepen.io/fbcouch/pen/eJYLBe
https://github.com/angular/angular.js/blob/master/src/ngRoute/route.js#L614
在Angular 1.x中,當一些數據從ajax到我的指令綁定('=')時,我在指令中看到這個綁定,我沒有正確地呈現指令。 我檢查了很多stackoverflow主題和博客以及他們寫的關於數據綁定和觀看的所有內容,但它對我沒有幫助,我親眼看到有時指令沒有呈現但是數據來了。
只有在指令中resolve
父控制器才能在這種情況下幫助我,因為在其他情況下它看起來像未定義的行為。 我從我的指令登錄,數據設置正常,但指令未呈現!(在簡單的情況下,我不使用ng-if或ng-show來隱藏它)。
你可以在這里閱讀更多
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.