【问题标题】:Angular Routing and Navigating角度路由和导航
【发布时间】:2021-10-01 23:29:54
【问题描述】:

我的app.component.html很轻

<div class="landing-page">
   <div class="main">
      <router-outlet></router-outlet>
      <div class="footer"> 
         <div class="logo-wrapper">
            <a routerLink="/"><img src="assets/images/logo.png" srcset="assets/images/logo@2x.png 2x,assets/images/logo@3x.png 3x" /></a>
         </div>
      </div>
   </div>
</div>

我在AppRoutingModule 中定义了以下路由:

const routes: Routes = [    
  { path: 'book/:id', component: BookComponent },
  { path: '**', component: LandingPageComponent }
];

在我的LandingPageComponent 中,我正在导航到book,如下所示:

constructor(private router: Router) { 
}

OpenBookComponent(id){        
    this.router.navigate(["/book", id], {skipLocationChange: true});
}

到目前为止,一切都很完美。

问题从导航到["/"]返回主页时开始

在浏览器中单击返回 &lt; 或以编程方式尝试从 BookComponent 导航到基本链接,在地址栏中显示完整路径(即:http://localhost:4200/book/123)并导致 仅显示页脚

我在BookComponent 中导航回来的代码是:

constructor(private route: ActivatedRoute, private router: Router) { 
    
}
ngOnInit() {        
    this.id = this.route.snapshot.paramMap.get('id');       
}
closeBook(){      
   this.router.navigate(["/"], {skipLocationChange: true});
}

返回时如何清除地址中的所有参数,使其仅保留/http://localhost:4200

【问题讨论】:

    标签: angular routes angular-routing navigateurl


    【解决方案1】:

    您不必删除参数。您必须像这样添加一条新路线:

    const routes: Routes = [
      { path: 'book/:id', component: BookComponent },
      { path: '', component: LandingPageComponent },
      { path: '**', component: LandingPageComponent }
    ];
    

    现在如果你想导航到"['/']",你可以这样写,例如:

    <a [routerLink]="['/']" class="nav-link active">Back</a>
    

    现在它将显示组件,您在 angular routes 数组中 '' 后面写入的位置,在本例中为 LandingPageComponent

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-25
      • 2021-01-13
      • 2020-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-03
      • 1970-01-01
      相关资源
      最近更新 更多