簡體   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