角度2:如何有条件地异步地将组件加载到Route中? [英] Angular 2: How to conditionally load a Component in a Route asynchronously?

查看:96
本文介绍了角度2:如何有条件地异步地将组件加载到Route中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在有条件的情况下,将组件异步附加到路由.

I'd like to attach a component to a route asynchronously, given a condition.

下面的示例有效(但异步),它根据用户角色加载一个或另一个组件:

The following example, which works (but is asynchronous), loads one component or another depending on the user role:

import { UserDashboardComponent }  from './user-dashboard.component'
import { AdminDashboardComponent } from './admin-dashboard.component'

const role = 'admin' // Just for the example
const comp = role === 'admin' ? AdminDashboardComponent : UserDashboardComponent

const routes: Routes = [
  { path: '', component: comp },
]

但是,假设我们要从API中检索角色,因此是异步的.有什么方法可以做到这一点?

But, let's say we want to retrieve the role from an API, thus asynchronous. What's the way to accomplish that?

推荐答案

您可以创建一个generic.module.ts,它将在声明数组中包含两个组件:

You could create a generic.module.ts which will have both components in declarations array:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { UserDashboardComponent }  from './user-dashboard.component'
import { AdminDashboardComponent } from './admin-dashboard.component    

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ UserDashboardComponent,AdminDashboardComponent ]
})
export class GenericModule { }

这样,您将拥有一个包含要加载的模块的模块.

this way you will have a module that contains the modules which you want to load.

现在,下一步将是使用编译器异步加载它们: 在组件内部执行以下操作:

Now next step will be to load them asynchronously using compiler: inside your component do following:

import {GenericModule} from './generic.module';
import { Component, Input,ViewContainerRef, Compiler, NgModule,ModuleWithComponentFactories,OnInit,ViewChild} from '@angular/core';
@Component({
  selector: 'generic',
  template: '<div #target></div>'
})
export class App implements AfterViewInit {
  @ViewChild('target', {read: ViewContainerRef}) target: ViewContainerRef;

  constructor(private compiler: Compiler) {}

  ngAfterViewInit() {
    this.createComponent('<u>Example template...</u>');
  }

  private createComponent(template: string,role:string) {
    @Component({template: template});
    const mod = this.compiler.compileModuleAndAllComponentsSync(GenericModule);
    const factory = mod.componentFactories.find((comp) =>
    //you can add your comparison condition here to load the component
    //for eg. comp.selector===role where role='admin'
    );
    const component = this.target.createComponent(factory);
  }
}

希望这会有所帮助.

这篇关于角度2:如何有条件地异步地将组件加载到Route中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆