为什么我在 AngularJS 中的路由不起作用?

路易吉·卡波格罗索

我是 AngularJS 的初学者,我想创建一个简单的登录和注册表单,但我的路由不起作用。

这是我的app.routing.ts

import { Routes, RouterModule } from '@angular/router';

import { HomeComponent } from './home/home.component';
import { RegistrationComponent } from './registration/registration.component';

const appRoutes: Routes = [
    { path: '', component: HomeComponent },
    { path: 'register', component: RegistrationComponent },
];

export const routing = RouterModule.forRoot(appRoutes);

这是app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { RegistrationComponent } from './registration/registration.component';
import { routing } from './app.routing';

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

这是app.component.html

<router-outlet></router-outlet>

我不明白为什么当我启动服务器时,默认页面是空的,而不是显示home.component.html 中包含的 html

我该如何解决?

上级

路由的顺序非常重要,因为它们是按照定义的顺序进行评估的。基本上,在您的示例中,Angular 检查空路由'',如果找到这样的路由,则HomeComponent应该加载 并且您看到的应该是home.component.html检查这一点的最简单方法是在home.component.html.

如果您需要显示RegistrationComponent空路由,我建议修改空路由的路由定义''

{ path: '', component: HomeComponent },
{ path: 'register', component: RegistrationComponent }

{ path: 'register', component: RegistrationComponent },
{ path: '', redirectTo: 'register', pathMatch: 'full' }

这样,Angular 将首先检查 url 是否与register路由匹配如果没有,它会检查它是否是''路由。如果是这种情况,则路由器将切换到register路由,这将加载RegistrationComponent.

希望这可以帮助。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章