角度路由不工作(错误:找不到站点)

问题描述 投票:0回答:2

在 NX workspace 中创建一个新的应用程序后,我目前正在使用两个组件。主页和产品列表页面。当我尝试创建路由器链接时,该站点显示“无法访问站点”的错误

这是我的应用程序模块 ts:

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

import { AppComponent } from './app.component';
import { RouterModule, Routes } from '@angular/router';
//import { appRoutes } from './app.routes';
import { HomePageComponent } from './pages/home-page/home-page.component';
import { ProductListComponent } from './pages/product-list/product-list.component';

const routes: Routes = [
  { path: '', component: HomePageComponent}, 
  { path:'products', component: ProductListComponent}
]

@NgModule({
  declarations: [
    AppComponent,
    HomePageComponent,
    ProductListComponent,
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes)
    //RouterModule.forRoot(appRoutes, { initialNavigation: 'enabledBlocking' }),
  ],
  providers: [],
  bootstrap: [AppComponent],
  
})


export class AppModule {}

自然地,我在我的应用程序组件(根)页面上声明了正确的路径:

<router-outlet></router-outlet>
angular angular2-routing
2个回答
0
投票

您编写的代码没有任何问题,我只需要知道您将router-outlet放在哪个组件中的功能?

你应该把 router-outlet 属性放在 app.component.html

我在一个原始项目中试过你的代码 我得到了一个完整的答案

希望我能帮上忙


0
投票

routes 对象没有默认路由,所以当您在浏览器中打开您的应用程序时,URL 是“http://localhost:4200/”并且该路由不在您的路由列表中。

这个问题的解决方案是将路由对象更改为这个:

    const routes: Routes = [
      { path: 'home', component: HomePageComponent},
      { path: 'products', component: ProductListComponent},
      { path: '', redirectTo: '/home', pathMatch: 'full'},
    ]

我在路线对象中做了这些改变:

  1. 将主页的路径从“”更改为“主页”。
  2. 在路由对象的末尾添加了默认路由(后备路由)。

当你使用角度路由时,你必须像这样定义一个默认路由:

  • 路径必须是“”(空字符串)。
  • 将 redirectTo 属性与主页的值一起使用(在您的情况下为“/home”)
  • 使用值为“full”的 pathMatch 属性,任何未在路由对象中定义的路由都将被重定向到您的主页。

提示:作为一个好的实践,我建议您创建一个 404 页面组件,当路径不存在时将用户重定向到该组件而不是您的主页。还可以在此处为可用路线放置一个导航菜单。

© www.soinside.com 2019 - 2024. All rights reserved.