如何在新的Router Angular 2中生成url路径

时间:2016-10-12 15:17:38

标签: angular angular-routing

新路由器3.0.0中的模拟deprecated-router方法generate是什么? 早期它可能需要这样的事情:

this._router.generate(['Profile']).urlPath;

新路由器怎么做?

2 个答案:

答案 0 :(得分:16)

https://angular.io/docs/ts/latest/api/router/index/Router-class.html#!#createUrlTree-anchor

var urlTree = this._router.createUrlTree(['Profile']);

您可以将结果传递给

this._router.navigate(/*string|UrlTree);

或获取网址

var url = this._router.createUrlTree(['Profile']).toString();

编辑:从Angular 6开始,您将结果传递给NavigateByUrl:

this._router.navigateByUrl(string|UrlTree);

答案 1 :(得分:4)

这些是Günter引用的页面中的当前示例

// create /team/33/user/11
router.createUrlTree(['/team', 33, 'user', 11]);

// create /team/33;expand=true/user/11
router.createUrlTree(['/team', 33, {expand: true}, 'user', 11]);

// you can collapse static segments like this (this works only with the first passed-in value):
router.createUrlTree(['/team/33/user', userId]);

// If the first segment can contain slashes, and you do not want the router to split it, you
// can do the following:

router.createUrlTree([{segmentPath: '/one/two'}]);

// create /team/33/(user/11//right:chat)
router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: 'chat'}}]);

// remove the right secondary node
router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: null}}]);

// assuming the current url is `/team/33/user/11` and the route points to `user/11`

// navigate to /team/33/user/11/details
router.createUrlTree(['details'], {relativeTo: route});

// navigate to /team/33/user/22
router.createUrlTree(['../22'], {relativeTo: route});

// navigate to /team/44/user/22
router.createUrlTree(['../../team/44/user/22'], {relativeTo: route});

https://angular.io/docs/ts/latest/api/router/index/Router-class.html#!#createUrlTree-anchor