我想动态加载菜单选项.所以我想知道最好的方法
我可以使用下面的代码在页面加载后添加路由.这适用于正常导航,但在刷新期间不起作用.
可以配置路由器返回一个承诺/如何将菜单项加载到路由中?
@inject(HttpClient)
export class DocumentMenu {
router: Router;
documents : IDocument[];
heading = 'Document Router';
constructor(public http: HttpClient) {}
activate(): void {
this.http.fetch('http://localhost:17853/Document/GetDocuments?folderID=13244')
.then<IDocument[]>(response => response.json())
.then<IDocument[]>(docs => {
if ( docs ){
for( var doc of docs){
this.router.addRoute( { route : doc.DocumentID.toString(), name : doc.Name, moduleId: './documents/document', nav:true, title: doc.Name });
}
this.router.refreshNavigation();
}
return docs;
});
}
configureRouter(config: RouterConfiguration, router: Router) {
var routes = new Array();
routes.push(
{ route: 'index', name: 'index-name', moduleId: './documents/index', nav: false, title: 'Documents' } );
routes.push( { route: '', redirect: 'index' } );
config.map( routes );
this.router = router;
}
}
Run Code Online (Sandbox Code Playgroud)
Mat*_*vis 10
这不能解答您的问题,但我认为这对您和其他有类似问题的人有帮助.
动态路线反模式
您的应用程序有许多不同的路由,所有路由都根据应用程序的状态而有所不同.因此,您必须先获取数据,然后构建路由,然后将其注册到路由器.
这是一种反模式的原因是因为当Aurelia本身使用描述动态内容的静态方式构建时,您将不断需要根据应用程序的状态更新路由器.
动态路由同构数据
假设您正在构建Google云端硬盘,并且您可以在用户添加和删除它们时更改各种文件.对于这种情况,您有两类路线:文件夹和文档.因此,您为每个路线制作一条路线.
configureRouter(config) {
config.map([
{ route: 'folder/:id', moduleId: 'folder' }
{ route: 'document/:id', moduleId: 'document' }
}
}
class FolderViewModel {
activate({ id }) {
// get your specific folder data and load it into your folder view model
this.fetch('getDocuments?folderId=${id}')
}
}
class DocumentViewModel {
activate({ id }) {
// get your specific document and load it into your document view model
this.fetch('getDocuments?documentId=${id}')
}
}
Run Code Online (Sandbox Code Playgroud)
动态路由异构数据
让我们说你想建立YouTube.当用户mjd10d登录时,欢迎他观看他心目中的视频,但他不是高级内容创建者,也无权访问该网站的内容创建部分.处理此问题的最佳方法是在应用程序中保留所有可能的路由,并根据用户的凭据过滤它们AuthorizeStep.
configureRouter(config, router) {
config.addPipelineStep('authorize', AuthorizeStep);
}
@inject(UserSession)
class AuthorizeStep {
constructor(UserSession) {
this.user = UserSession;
}
run(navigationInstruction, next) {
var instructions = navigationInstruction.getAllInstructions()
if (!this.authorized(instructions.config)) {
return Redirect('404');
}
return next();
}
authorized(routeConfig) {
// something smart that returns false if unauthorized
return this.user.permissionLevel > routeConfig.requiredPermission;
}
}
Run Code Online (Sandbox Code Playgroud)
虽然并非所有情况都与授权相关,但您始终可以使用addPipelineStep API 注册自己的管道步骤