为什么选择初始加载页面时出现错误?

时间:2018-10-05 12:49:54

标签: javascript angular typescript

当我在功能模块GalleryModuleModule中选择上载的初始组件时,此组件GalleryComponent

我收到此错误:

  

Invalid configuration of route '': Array cannot be specified(所有组件都在GalleryModuleModule中)。告诉我我在做什么错以及如何解决这个问题?

应用模块:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { GalleryModuleModule } from './gallery-module/gallery-module.module';

@NgModule({
    declarations: [
        AppComponent,
    ],
    imports: [
        BrowserModule,
        GalleryModuleModule,
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule {
}

app.component.html:

<div class="container">
    <router-outlet></router-outlet>
</div>

gallery-module.module:

import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {GalleryComponent} from "./gallery/gallery.component";
import {GalleryAddComponent} from './gallery/gallery-add/gallery-add.component';
import {RouterModule, Routes} from "@angular/router";

const appRoutes: Routes = [
    {path: '', redirectTo: '/gallery', pathMatch: 'full'},
    {path: 'gallery-add', component: 'GalleryAddComponent'},
];

@NgModule({
    imports: [
        CommonModule,
        RouterModule.forRoot([
            appRoutes,
            {enableTracing: true}
        ])
    ],
    declarations: [GalleryComponent, GalleryAddComponent],
    exports: [GalleryComponent, GalleryAddComponent RouterModule],
})
export class GalleryModuleModule {
}

2 个答案:

答案 0 :(得分:1)

您做了{path: '', redirectTo: '/gallery', pathMatch: 'full'},,但实际上您没有名为gallery的路径应重定向到。 例如,将您的路由配置更改为:

const appRoutes: Routes = [
    {path: '', redirectTo: '/gallery', pathMatch: 'full'},
    {path: 'gallery', component: GalleryComponent},
    {path: 'gallery-add', component: GalleryAddComponent},

];

并删除RouterModule.forRoot()https://angular.io/api/router/RouterModule#forRoot)中的多余数组(如@Suresh所述)应该可以工作!

PS :不要忘记导入您的路由配置中列出的组件(它们不应用字符串引用

答案 1 :(得分:0)

请参阅仅在根路由器模块App.module.ts中定义RouterModule.forRoot()。但是,您需要在导入到app.module.ts中的子模块“ GalleryModuleModule”中定义这些根路由。

import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {GalleryComponent} from "./gallery/gallery.component";
import {GalleryAddComponent} from './gallery/gallery-add/gallery-add.component';
import {RouterModule, Routes} from "@angular/router";

const appRoutes: Routes = [
    {path: '', redirectTo: '/gallery', pathMatch: 'full'},
    {path: 'gallery-add', component: 'GalleryAddComponent'},
];

@NgModule({
    imports: [
        CommonModule,
        RouterModule.forRoot(
            appRoutes,
            {enableTracing: true}
        )
    ],
    declarations: [GalleryComponent, GalleryAddComponent],
    exports: [GalleryComponent, GalleryAddComponent RouterModule],
})
export class GalleryModuleModule {
}