如何从路由代码生成网址? 例如,我的路线中有一个登录组件:
const appRoutes: Routes = [
...
{ path: 'login', component: LoginComponent },
...
];
我想构建一个与我的登录组件的url对应的字符串:
let url = "I don't know";
console.log(url); ----> 'http:localhost:4200/login'
答案 0 :(得分:4)
您可以注入Router
和UrlSerializer
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);
另见