繁体   English   中英

如何在 Angular 中使用相同的组件进行路由

[英]How to use same Component for routing in Angular

我为我的路由器使用相同的组件,第一次单击受影响的组件,但在下一次单击该组件仍位于第一个 state 中。

这是更改路线的脚本

<a [routerLink]="['react/1']">link 1</a>
<a [routerLink]="['react/2']">link 2</a>

这是我的路由器模块

面板路由.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router'
import { PanelCoursesComponent } from 'src/app/components/panel-courses/panel-courses.component';
import { PanelHomeComponent } from 'src/app/components/panel-home/panel-home.component';
import { PanelIntroComponent } from 'src/app/components/panel-intro/panel-intro.component';

const routes: Routes = [
    { path: '', component: PanelHomeComponent },
    { path: 'react', component: PanelIntroComponent },
    { path: 'react/:no', component: PanelCoursesComponent } //the target
]

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class PanelRoutingModule { }

面板课程.component.ts

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router'

@Component({
  selector: 'app-panel-courses',
  templateUrl: './panel-courses.component.html',
  styleUrls: ['./panel-courses.component.scss']
})
export class PanelCoursesComponent implements OnInit {
  url!: any

  constructor(private route: ActivatedRoute, private router: Router) {
    console.log('route')
  }

  ngOnInit(): void {
    this.url = this.router.url
    console.log(this.route.snapshot.params) //the test script
  }

}

在 PanelCourseComponent 上,我尝试控制台记录参数,但这仅在第一次单击时执行一次。

我错过了什么吗?

对于这种情况,您可以使用this.route.params.subscribe方法

这是示例

ngOnInit(): void {
    this.route.params.subscribe(params => {
      console.log(params) // It will be executed whenever you click the link
    })
  }

默认情况下pathMatch设置为'prefix' 因此路径将与您当前的位置进行匹配,第一个“匹配”将呈现其组件。 要使您的路径仅匹配“精确”匹配,请为您的路线添加pathMatch: 'full'

const routes: Routes = [
    { path: '', component: PanelHomeComponent, pathMatch: 'full' },
    { path: 'react', component: PanelIntroComponent, pathMatch: 'full' },
    { path: 'react/:no', component: PanelCoursesComponent } //the target
]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM