Angular 2-匹配URL以进行路由 [英] Angular 2 - Match URL to Route

查看:74
本文介绍了Angular 2-匹配URL以进行路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以采用URL或路径,并在后面的代码中找出与之匹配的路由?

Is it possible to take a URL or path and find out which route it matches in the code-behind?

例如: Router.matchRoute('my/route')返回有关匹配路由的信息,例如:

Ex: Router.matchRoute('my/route') returns information about the matching route, like:

{
  path: 'my/route',
  component: HeroListComponent,
  data: { title: 'Heroes List' }
}

基本上,我要尝试的是判断当前URL/路径的路由是否与导航到的URL/路径匹配.

Basically, what I'm trying to do is to tell if the route of my current URL/path matches that of the one being navigated to.

推荐答案

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

这篇关于Angular 2-匹配URL以进行路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆