路由行为没有按预期工作

Routing behavior not working as expected

本文关键字:工作 路由      更新时间:2023-09-26

我在我的app-routing.module.ts中定义了以下路由变量:

const routes: Routes = 
[
  { path: '', redirectTo: '/users', pathMatch: 'full' }, 
  { path: 'users',  component: UsersComponent },
  { path: 'dashboard',  component: DashboardComponent }
];

使用当前的配置,当我提交http://localhost:3000/users时,浏览器将重定向到http://localhost:3000/users/users,然后按预期在html中显示用户列表绑定。

但是,对于浏览器来说,从/users重定向到/users/users似乎有些不平衡。如果我删除了带有redirectTo属性的第一个路由配置,那么浏览器将停留在/users上,而不会重定向到/users/users。然而,在这个场景中,用户列表绑定没有按预期显示。

你知道是什么原因导致重定向到/users/users吗?我怎么能保持浏览器在/users和获得用户列表绑定正确显示在这个uri?

选项1:设置基标签

为了让路由器正常工作,需要在应用中定义一个基本的href。文档建议在index.html文件的头部添加一个基本元素,比如:

<base href="/">

选项2:设置提供商

这可能有点危险,因为它对锚标记,空的href标记等有(可能意想不到的)副作用。它还破坏了内联svg精灵…这是我们应用UI的主要部分。如果你想让路由器工作,但不破坏很多东西,你可以在其他地方定义基本的href,像这样:

// ... other imports
import { APP_BASE_HREF } from '@angular/common';
@NgModule({
    
    // ... other pieces of ngModule
    
    providers: [
        {provide: APP_BASE_HREF, useValue : '/' }
    ],
    
    // ... other pieces of ngModule
})
export class AppModule {
    constructor() {}
}

是一个基本的例子。在文档中很难找到,但这是一个很好的解决方案,可以让事情顺利进行,而不会干扰其他所有内容。