如何通过代码从路由生成URL?例如,我在我的路由中有一个登录组件:
const appRoutes: Routes = [
...
{ path: 'login', component: LoginComponent },
...
];
我想构建一个字符串,表示我的登录组件的URL:
let url = "I don't know";
console.log(url); ----> 'http:localhost:4200/login'
路由器(Router)
和URL序列化器(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
时,它将从该路由开始应用给定的命令。当未指定路由时,它将从根路由开始应用给定的命令。Location
并使用其相应方法。let fullUrl = window.location.origin + location.prepareExternalUrl(url);
另请参阅
let tree = router.createUrlTree(['login']); let url = urlSerializer.serialize(tree); let fullUrl = location.prepareExternalUrl(url);
- Benlet fullUrl = location.prepareExternalUrl(window.location.origin + url);
- Benwindow.location.origin + location.prepareExternalUrl(url)
对我有用(请参考 Plunker)。 - Günter Zöchbauer