angular6 监听url变化

前端之家收集整理的这篇文章主要介绍了angular6 监听url变化前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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的查询参数
      }
    });
  }
}

猜你在找的Angularjs相关文章