How to handle query parameters in angular 2

后端 未结 12 803
灰色年华
灰色年华 2020-11-27 03:41

In my routable component I have

@RouteConfig {
  {path: \'/login\',   name: \'Login\', component: LoginComponent}
}  

But how

12条回答
  •  猫巷女王i
    2020-11-27 04:08

    To complement the two previous answers, Angular2 supports both query parameters and path variables within routing. In @RouteConfig definition, if you define parameters within a path, Angular2 handles them as path variables and as query parameters if not.

    Let's take a sample:

    @RouteConfig([
      { path: '/:id', component: DetailsComponent, name: 'Details'}
    ])
    

    If you call the navigate method of the router like this:

    this.router.navigate( [
      'Details', { id: 'companyId', param1: 'value1'
    }]);
    

    You will have the following address: /companyId?param1=value1. The way to get parameters is the same for both, query parameters and path variables. The difference between them is that path variables can be seen as mandatory parameters and query parameters as optional ones.

    Hope it helps you, Thierry

    UPDATE: After changes in router alpha.31 http query params no longer work (Matrix params #2774). Instead angular router uses so called Matrix URL notation.

    Reference https://angular.io/docs/ts/latest/guide/router.html#!#optional-route-parameters:

    The optional route parameters are not separated by "?" and "&" as they would be in the URL query string. They are separated by semicolons ";" This is matrix URL notation — something you may not have seen before.

提交回复
热议问题