且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Angular 2 - 将 URL 匹配到路由

更新时间:2021-12-25 14:54:57

如果你想获取当前 URL 并根据它在组件代码中做出一些决定,例如添加一个样式来为当前项目着色导航菜单,然后您可以从路由器获取当前 URL 并将其与已知值进行比较以执行某些操作.

If you want to get the current URL and make some decisions in the component code based on what it is, for example adding a style to colour the current item in a navigation menu, then you can get the current URL from the Router and compare it to a known value to do something.

 import { Router } from '@angular/router';

 constructor(
    private router: Router
 ) {}

然后您可以编写函数来检查特定路线:

Then you can write functions to check for a particular route:

 isSomePage() {
    if (this.router.url.includes('/my-page-path/')) {
        return 'active';
    } else {
        return '';
    }
 }

然后将 thing 函数绑定到 ngClass 以将类(活动)添加到该项目并使用 css 设置样式.

And then bind thing function to ngClass to add the class (active) to that item and style it with css.

 <div [ngClass]="isSomePage()">
    "colour me when the URL matches the isSomePage function"
 </div>

然后通过 css 设置样式

Then style this via css

div.active {
    color: white;
    background-color: red;
}

如果您待在一个地方并想要监控 URL 的变化,您可以订阅 router.events,例如,如果您通过如下 URL 传递id"变量:

In the case where you're staying in one place and want to monitor the URL for changes, you can subscribe to router.events, for example if you were passing an 'id' variable via URL like this:

http://localhost:4000/#/home/my-component/?id=1146605

您可以订阅 id 值的更改 - 在此示例中,我将值记录到控制台,但您可以在此处获取该值后做任何您喜欢的操作.

You could subscribe to the changes in id values - in this example I'm logging the values to the console, but you can do whatever you like with the value once you've got it here.

import { Router, NavigationEnd, Params } from '@angular/router';

var routerPassedParam

  ngOnInit() {
    this.router.events
      .filter(event => event instanceof NavigationEnd)
      .subscribe(event => {
        console.log("event", event);
        this.route
          .queryParams
          .subscribe(params => {
            // Defaults to 0 if no query param provided.
            var routerPassedParam = +params['id'] || 0;
            console.log('Query param routerPassedParam: ', routerPassedParam);
          });
      })
}