How to serialize ActivatedRoute for a string in Angular 2?

I am trying to create a palette to display in my shell component (one with <router-outlet> ). I insert the Angular Router service and moving it from routerState.root down the firstChild (or children[0] ) property to a null value, creating a (linked) list of components containing the current displayed route. The result is a linked list of ActivatedRoute objects. Since I am attaching user data to every specific route (e.g. name) that I can get (via ActivatedRoute.data member) at runtime, so I can display the names of the elements in breadcrumbs.

But the problem is with links (urls). ActivatedRoute has all the information about a specific route in the chain, but I could not find a way to serialize it for a single-line value, to use it as a reference in breadcrumb. I could manually disassemble it, of course, but this is too much work for something so important. ActivatedRoute has URLs (segmented by itself), query parameters, matrix parameters, etc. all in different properties (some of them even Observables to unnecessarily complicate things) ... but not one single line property that gives full URLs (with params and all that).

By the way, the Router service has a member serializeUrl() , which takes a parameter of type UrlTree and converts it to a string. Maybe there is a method that converts ActivatedRoute to UrlTree so that I can then use Router.serializeUrl() ? ..

Simple: How can I get a serialized string from an ActivatedRoute (or ActivatedRouteSnapshot ) object? (Without writing all the parsing logic, obviously).

This seems to be necessary, since ActivatedRoute essentially parses the representation of the string url (if I understand this whole concept correctly) ... and Router even has a helper method for building an UrlTree object (which never explains how to get it first) ...

+6
source share
2 answers

router.createUrlTree can get ActivatedRoute .

 @Component({ selector: "foo" }) class Foo { constructor(router: Router, route: ActivatedRoute) { const urlTree = router.createUrlTree(["."], { relativeTo: route }); console.log(router.serializeUrl(urlTree)); } } 
+1
source

Try it:

 this.route.children[0].url.value 

It must be an array containing an UrlSegmen object with a field. One UrlSegment = one route route

0
source

Source: https://habr.com/ru/post/1013531/


All Articles