angular组件的类中的ngOnInit方法只会在页面首次加载时执行,当我们在页面中需要根据不同的url查询参数显示不同的内容时,就需要监听url的变化。
import { Component,OnInit } from ‘@angular/core‘; import { Router,NavigationEnd,ActivationEnd } from ‘@angular/router‘; @Component({ selector: ‘app-root‘,templateUrl: ‘./app.component.html‘,styleUrls: [‘./app.component.css‘] }) export class AppComponent implements OnInit { constructor(private router: Router) { this.router.events.subscribe((event: NavigationEnd) => { if (event instanceof ActivationEnd) { sort = event.snapshot.queryParams.sort; // sort为url的查询参数 } }); } }