我测试了这个片段:
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Component({
selector: 'app-about',
templateUrl: './about.component.html',
styleUrls: ['./about.component.css']
})
export class AboutComponent implements OnInit {
random;
constructor(private router: Router) {
console.log(this.router.onSameUrlNavigation);
this.router.onSameUrlNavigation = 'reload'
this.router.events.subscribe(event => {
if (!(event instanceof NavigationEnd)) { return; }
this.random = Math.random();
});
}
ngOnInit() {
}
}

<div class="page-header">
<div class="container">
<h1>Router Sample</h1>
<div class="navLinks">
<a [routerLink]="['/about']">About Us</a>
</div>
</div>
</div>
<div id="content">
<div class="container">
<router-outlet></router-outlet>
</div>
</div>
这是一个模板儿童:
<h1>random : {{random}}</h1>
<p>
about works!
</p>
&#13;
如何在点击同一链接后生成新的随机数? 如果我点击相同的链接&#34;关于我们&#34;,随机数是相同的。
测试:NavigationEnd
//app modlule
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { AboutComponent } from './about/about.component';
const appRoutes: Routes = [
{ path: 'about', component: AboutComponent },
];
@NgModule({
declarations: [
AppComponent,
AboutComponent
],
imports: [
RouterModule.forRoot(
appRoutes,
{ enableTracing: true } // <-- debugging purposes only
),
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
&#13;
//about.ts
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Component({
selector: 'app-about',
templateUrl: './about.component.html',
styleUrls: ['./about.component.css']
})
export class AboutComponent implements OnInit {
random;
constructor(private router:Router) {
console.log("click route again");
this.router.events.subscribe(event => {
if(!(event instanceof NavigationEnd)) { return; }
this.random = Math.random();
});
}
ngOnInit() {
}
}
&#13;
我用NavigateEnd尝试这个片段,ne随机没有变化?可能是我忘了别的什么?
答案 0 :(得分:1)
订阅路由器事件,检查事件是否为导航结束,然后执行操作。
constructor(private router: Router) {
this.router.events.subscribe(event => {
if(!(event instanceof NavigationEnd)) { return; }
this.random = Math.random();
});
}