Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
931 views
in Technique[技术] by (71.8m points)

angular - Angular2 with matrix url notation

Is the matrix url notation the "default" to creating urls with parameters or is better to use the "old" notation with ? and &. I didn't understand it on the angular.io documentation

localhost:3000/heroes;id=15;foo=foo

or

localhost:3000/heroes?id=15&foo=foo
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 navigate

    router.navigate(['/foo'], { queryParams: { bar: 1, baz: 2 }});
    

    Here you get /foo?bar=1&baz=2

See also:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...