且构网

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

Angular 2-匹配URL以进行路由

更新时间:2022-05-12 17:14:10

如果要获取当前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);
          });
      })
}