2017-05-06 24 views
2

我有这样一本教科书途径得到的副路径:角2如何从URL

{ path: "browse/:id", component: BrowseComponent }, 

我想要做的是能得到的尾部路径的一部分,当激活路由像

http://localhost:4200/browse/a/b/c/d 

因此,id将设置为“a/b/c/d”。有没有这样做的标准方式?

回答

2

你可以通过提供一个路线匹配键使用UrlMatcher的路径。遗憾的是它没有证件的,因此您可能需要检查路由器/ src目录/ config.ts来源:

/** 
* @whatItDoes Represents the results of the URL matching. 
* 
* * `consumed` is an array of the consumed URL segments. 
* * `posParams` is a map of positional parameters. 
* 
* @experimental 
*/ 
export type UrlMatchResult = { 
    consumed: UrlSegment[]; posParams?: {[name: string]: UrlSegment}; 
}; 

/** 
* @whatItDoes A function matching URLs 
* 
* @description 
* 
* A custom URL matcher can be provided when a combination of `path` and `pathMatch` isn't 
* expressive enough. 
* 
* For instance, the following matcher matches html files. 
* 
* ``` 
* function htmlFiles(url: UrlSegment[]) { 
* return url.length === 1 && url[0].path.endsWith('.html') ? ({consumed: url}) : null; 
* } 
* 
* const routes = [{ matcher: htmlFiles, component: HtmlCmp }]; 
* ``` 
* 
* @experimental 
*/ 
export type UrlMatcher = (segments: UrlSegment[], group: UrlSegmentGroup, route: Route) => 
UrlMatchResult; 

这基本上可以让你写,可以做任何类型的匹配,包括正则表达式的功能。

它仍然是实验性的,所以没有太多的例子,但github/matanshukry已经提供了ComplexUrlMatcher的一个主要例子。它应该给你一个想法如何实现一个适合你的需求(遗憾的是没有许可证,所以你不能使用它)。

更多信息链接

http://blog.devcross.net/2016/03/25/angular-2-router-and-regular-expressions/

1

晚来回答,但如果仍然有同样的问题在这里是我如何解决同样的问题..

这是我的路线

{ 
    path: 'browse', 
    component: ParentBrowseComponent, 
    children : [{ 
     path: '**', 
     component: BrowseComponent 
    }] 
} 

我已将browse定义为父路由,并定义了**子路由。子女使用BrowseComponent作为组件,父母使用ParentBrowseComponent

在我BrowseComponent构造我检测URL变化使用这样

import { Router, ActivatedRoute, ParamMap, NavigationStart, NavigationEnd } from '@angular/router'; 

_router.events.subscribe((val) => { 
    console.log(val); 
    if(val instanceof NavigationEnd) { 
     var url = this._router.url; 
     //do anything with url 
    } 
}); 

导入的路由这将让我当前路线

例如在这种情况下,路线

http://localhost/browse/a/b/c/d

它会给我

/浏览/ A/B/C/d

您可以轻松地操纵这个网址为您的使用。

想知道是什么你的父母compoenent成立,只是一个<router-outlet></router-outlet>

+0

是的,所有的东西都在一个router-outlet元素之下,传统的编码是使用URL参数(比如?xx = abc ),但我期待着一个只有“干净”URL的世界。感谢您的提示。 – AlanObject