22

条件を指定して、ルートにコンポーネントを非同期的にアタッチしたいと思います。

次の例は機能しますが (ただし非同期です)、ユーザーの役割に応じて、1 つまたは別のコンポーネントを読み込みます。

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 からロールを取得したいとしましょう。つまり、非同期です。それを達成する方法は何ですか?

4

6 に答える 6

9

宣言配列に両方のコンポーネントを持つ generic.module.ts を作成できます。

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 { }

このようにして、ロードしたいモジュールを含むモジュールができます。

次のステップは、コンパイラを使用してそれらを非同期にロードすることです。コンポーネント内で次の操作を行います。

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);
  }
}

お役に立てれば。

于 2016-10-04T15:17:26.057 に答える
8

Angular 2 は、モジュール レベルでの遅延読み込みをサポートしています。機能モジュールは、コンポーネントではなく非同期で読み込まれます。そのコンポーネント機能モジュールを作成できます。 https://angular.io/docs/ts/latest/guide/ngmodule.html

于 2016-09-25T16:19:21.590 に答える
1

ルーターの navigate メソッドを使用して、プログラムでナビゲートすることをお勧めします。したがって、ルーターファイルに考えられるすべてのルートをリストします。次に、コンポーネントで、特定のケースに基づいて router.navigate() を呼び出します。

于 2016-09-25T18:26:15.790 に答える