我正在开展Angular项目,我在路由方面遇到问题。
我的导航栏代码如下
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']);
}
}
注意:我的其他路线工作正常,所以工作正常
首先,确保你的html文件中有<router-outlet></router-outlet>
。
其次,在MatchCenterComponent的ngOnInit()
中,您将参数'matchname'
转换为整数,但由于它将是Football或Cricket,它将导致NaN。
第三,在ngOnInit()
中,你正在导航到['/matchcenter',matchName]
,但这将返回一个MatchCenterComponent,所以你将处于无限循环中。