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

时间:2019-01-14 09:17:22

标签: angular angular-ui-router angular5 angular6 angular-routing

我正在做一个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/Football 要么 http://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']);
  }
}

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

1 个答案:

答案 0 :(得分:0)

首先,请确保您的html文件中包含<router-outlet></router-outlet>

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

第三,在ngOnInit()中,您也导航到['/matchcenter',matchName],但这将返回MatchCenterComponent,因此您将陷入无休止的循环。