Angular 2 - 将 URL 匹配到路由 [英] Angular 2 - Match URL to Route

查看:35
本文介绍了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/路径的路由是否与被导航到的路由匹配.

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天全站免登陆