Angular如何从ActivatedRouteSnapshot获取UrlSegment的segments数组?
Hey there! I totally get why you’re avoiding those underscore-prefixed private properties—they’re internal implementation details that can break unexpectedly with Angular updates. Lucky for you, Angular provides a clean, public API to get those URL segments directly. Here are two reliable ways to do it:
1. Use the url Public Property
The ActivatedRouteSnapshot has a built-in public property called url that returns exactly the UrlSegment[] you’re looking for. No need to mess with private _urlSegment at all:
canActivateChild(childRoute: ActivatedRouteSnapshot) { // This gives you the UrlSegment array directly const segments = childRoute.url; console.log('Current Route URL Segments:', segments); // Example: Access individual segment paths segments.forEach(segment => { console.log('Segment Path:', segment.path); }); return true; }
This property is part of Angular’s official public API, so it’s safe to use across versions.
2. Get Full Path Including Parent Routes
If you need the complete URL segments from the root route down to the current child route, use pathFromRoot to iterate through all ancestor route snapshots and collect their segments:
canActivateChild(childRoute: ActivatedRouteSnapshot) { const allSegments = childRoute.pathFromRoot .map(routeSnapshot => routeSnapshot.url) .flat(); // Flattens nested arrays into a single array of UrlSegments console.log('Full URL Segments (Root to Child):', allSegments); return true; }
This is useful if your child route is nested deep and you need the full context of the URL path.
Why Avoid Private Properties?
Just to reinforce: Properties prefixed with _ in Angular are marked as private/internal. Angular’s team doesn’t guarantee these will stay the same between versions—they could rename, remove, or change how they work without warning. Sticking to public APIs like url ensures your code stays stable.
内容的提问来源于stack exchange,提问作者Kamran Khatti

