Angular2从Routes(typescript)反向/生成url

时间:2016-10-15 11:04:43

标签: url angular build routes reverse

如何从路由代码生成网址? 例如,我的路线中有一个登录组件:

const appRoutes: Routes = [
    ...
    { path: 'login', component: LoginComponent },
    ...
];

我想构建一个与我的登录组件的url对应的字符串:

let url = "I don't know";
console.log(url); ----> 'http:localhost:4200/login'

1 个答案:

答案 0 :(得分:4)

您可以注入RouterUrlSerializer

constructor(router: Router, urlSerializer: UrlSerializer, route: ActivatedRoute) {
  let tree = router.createUrlTree(['/path', param, 'otherPath'], { relativeTo: route, queryParams: {y: z} });
  let url = urlSerializer.serialize(tree);
}

router.createUrlTree给出如上所述的激活路线时,它会从路线开始应用给定的命令。如果没有给出路由,它将从根开始应用给定的命令。

要获取URL的静态部分,您可能需要注入Location并使用

let fullUrl = window.location.origin + location.prepareExternalUrl(url);

另见

Plunker example