在路径中更改参数时,无法再次读取参数和面临加载组件的问题

问题描述 投票:0回答:1

我正在开展Angular项目,我在路由方面遇到问题。

  1. 一旦通过路线选择导航栏中的任何选项,我就无法读取参数。
  2. 一旦路线参数发生变化,我就无法重新加载组件

我的导航栏代码如下

TS文件

export class HeaderComponent implements OnInit {
  navLinks:any;
  token: any;
  responsesportstypedata: any;
  store = [];
  matchname: any;

  constructor(  private rest : ServicesService , public router : Router ) {
    console.log(location.pathname);

    this.loadDataFromApi();
  }

  ngOnInit() {}

  getMatchid(val){
 this.router.navigate(['matchcenter',val]);
    }
     loadDataFromApi() {
     this.token =  localStorage.getItem('putoken');
      console.log('token == ' + this.token);
     this.rest.getSportstype().then(
      result => {
       this.responsesportstypedata = result;
       this.store = this.responsesportstypedata;


       },
    }

HTML

<div (click)='getMatchid(item.ttypeUid)'>{{item.ttypeName})</div>

APP-routing.module.ts

const routes: Routes = [

 { path: 'matchcenter' , component: MatchcenterComponent},
 { path: 'matchcenter/:matchname' , component: MatchcenterComponent}

];

在路径http://localhost:4200/matchcenter/:matchname,我动态地传递matchname,

它可以是http://localhost:4200/matchcenter/Footballhttp://localhost:4200/matchcenter/Cricket

一旦组件MatchcenterComponent被加载但是在路径更改组件的参数上,MatchcenterComponent不会重新加载

以下代码适用于MatchcenterComponent。

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

@Component({
  selector: 'app-matchcenter',
  templateUrl: './matchcenter.component.html',
  styleUrls: ['./matchcenter.component.scss']
})
export class MatchcenterComponent implements OnInit {

  constructor(public rest : ServicesService , public router : Router , public dialog: MatDialog , public _route: ActivatedRoute ) {
    console.log('matchcenterPage');
    console.log(location.pathname);
    this.loadDataFromApi();
   }   
  ngOnInit() {

     const id = +this._route.snapshot.paramMap.get('matchname');
    this.router.navigate(['/matchcenter',matchName]);
    console.log('+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++' + matchName);
      //  this.router.navigate(['matchcenter/Cricket']);
  }
}

注意:我的其他路线工作正常,所以工作正常

angular angular-ui-router angular5 angular6 angular-routing
1个回答
0
投票

首先,确保你的html文件中有<router-outlet></router-outlet>

其次,在MatchCenterComponent的ngOnInit()中,您将参数'matchname'转换为整数,但由于它将是Football或Cricket,它将导致NaN。

第三,在ngOnInit()中,你正在导航到['/matchcenter',matchName],但这将返回一个MatchCenterComponent,所以你将处于无限循环中。

© www.soinside.com 2019 - 2024. All rights reserved.