问题描述
我的app.component.html:
我的app-routing.module.ts
import { NgModule } from '@angular/core';从'@angular/common'导入{CommonModule};从@angular/router"导入 { RouterModule, Routes };从'./components/menu/menu.component'导入{菜单组件};从 './components/blog/blog.component' 导入 { BlogComponent };从 './components/team/team.component' 导入 { TeamComponent };const 路由:路由 = [{ 路径:'',组件:MenuComponent },{ 路径:'**',组件:MenuComponent },{路径:'菜单',组件:菜单组件},{ 路径:'博客',组件:BlogComponent },{ 路径:'团队',组件:TeamComponent }];@NgModule({进口:[RouterModule.forRoot(路由)],出口:[路由器模块]})导出类 AppRoutingModule { }
当我在 url 中写入路由时(即 http://localhost:4200/blog) 没有给出错误,但我留在 MenuComponent 中.此外,当我刷新时,链接保持 http://localhost:4200/blog.
我错过了什么吗?
P.S:如果需要任何代码,我可以编辑我的问题以显示它,不要立即投票:)
你需要对路由进行排序,路由器正在寻找第一个匹配项,也就是你的菜单组件,试试这个.
const 路由:Routes = [{路径:'菜单',组件:菜单组件},{ 路径:'博客',组件:BlogComponent },{ 路径:'团队',组件:TeamComponent },{ 路径:'',组件:MenuComponent },{ 路径:'**',组件:MenuComponent }];
配置中路由的顺序很重要,这是设计使然.路由器在匹配路由时使用先匹配获胜策略,因此更具体的路由应该放在不太具体的路由之上.在上面的配置中,首先列出具有静态路径的路由,然后是与默认路由匹配的空路径路由.通配符路由排在最后,因为它匹配每个 URL,并且只有在没有其他路由首先匹配时才应该被选中.
来自 angular 网站这里
My app.component.html:
<router-outlet></router-outlet>
my app-routing.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { MenuComponent } from './components/menu/menu.component';
import { BlogComponent } from './components/blog/blog.component';
import { TeamComponent } from './components/team/team.component';
const routes: Routes = [
{ path: '', component: MenuComponent },
{ path: '**', component: MenuComponent },
{ path: 'menu', component: MenuComponent },
{ path: 'blog', component: BlogComponent },
{ path: 'team', component: TeamComponent }
];
@NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [RouterModule]
})
export class AppRoutingModule { }
When I write the route in the url to go to (i.e. http://localhost:4200/blog) no error is given but I stay in the MenuComponent. Also when I refresh, the link stays http://localhost:4200/blog.
Am I missing something?
P.S: If any code is needed I can edit my question to show it, do not downvote immediately :)
You need to order your routes, the router is finding the first match, which is your menu component, try this.
const routes: Routes = [
{ path: 'menu', component: MenuComponent },
{ path: 'blog', component: BlogComponent },
{ path: 'team', component: TeamComponent },
{ path: '', component: MenuComponent },
{ path: '**', component: MenuComponent }
];
From angular website here
这篇关于Angular 8 路由器不重定向到路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!