Angular2 with matrix url notation
Matrix parameters are tied to a path segment, while query parameters are tied to the URL. They have different semantics. Use whichever one is more appropriate. (see links in "see also" below").
Maybe it's hard to tell because you always see it at the end of the URL, but this is also matrix paramters
localhost:3000/heroes;id=15;foo=foo/bar/baz
The parameters are tied to heroes
. When you access the route.url
, you will see this
this.route.url.subscribe((url: UrlSegment[]) => {
let heroes = url[0];
let heroesMatrix = heroes.parameters();
// heroes should contain id=5, foo=foo
let bar = url[1].path;
let baz = url[2].path;
})
Is the matrix url notation the "default" to creating urls with parameters or is better to use the "old" notation with ?
No, both could be used, and how to use (create) them is completely different
matrix parameters are tied to each path segment, by passing an object after the path element in the array
router.navigate(['/foo', { id:1 }, 'bar', {baz: 2 } ])
Here you will get
/foo;id=1/bar;baz=2
query parameters are created by passing the
NavigationExtras
as the second argument to navigaterouter.navigate(['/foo'], { queryParams: { bar: 1, baz: 2 }});
Here you get
/foo?bar=1&baz=2
See also:
- When to use query parameters versus matrix parameters?
- URL matrix parameters vs. request parameters
UPDATE (disclaimer)
If you read the Angular documentation on optional parameters, they feel that the above semantics are not really important in regards to working with Angular. I'd probably have to agree. The semantics are more important with REST APIs.
With an Angular app, the only people who really care about these parameters are us the developer. The user doesn't care. It is not a REST API where we should stick to well known semantics. For out Angular app, as long as we the developer know how to use params (whether matrix or query), it shouldn't matter which one we use.
That being said, matrix params are less verbose to code, so personally, I'd say that using the matrix params might be the best way to go.
For matrix parameters you can also subscribe to params instead of peeling them out of url.
this.paramSubscription = this.activeRoute.params.subscribe(params => {
const bar = params['bar'];
const baz = params['baz'];
});