How to handle query parameters in angular 2

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

In my routable component I have

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

But how

相关标签:
12条回答
  • 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.

    0 讨论(0)
  • 2020-11-27 04:10

    Angular 4:

    I have included JS (for OG's) and TS versions below.

    .html

    <a [routerLink]="['/search', { tag: 'fish' } ]">A link</a>
    

    In the above I am using the link parameter array see sources below for more information.

    routing.js

    (function(app) {
        app.routing = ng.router.RouterModule.forRoot([
            { path: '', component: indexComponent },
            { path: 'search', component: searchComponent }
        ]);
    })(window.app || (window.app = {}));
    

    searchComponent.js

    (function(app) {
        app.searchComponent =
            ng.core.Component({
                selector: 'search',
                    templateUrl: 'view/search.html'
                })
                .Class({
                    constructor: [ ng.router.Router, ng.router.ActivatedRoute, function(router, activatedRoute) {
                    // Pull out the params with activatedRoute...
                    console.log(' params', activatedRoute.snapshot.params);
                    // Object {tag: "fish"}
                }]
            }
        });
    })(window.app || (window.app = {}));
    

    routing.ts (excerpt)

    const appRoutes: Routes = [
      { path: '', component: IndexComponent },
      { path: 'search', component: SearchComponent }
    ];
    @NgModule({
      imports: [
        RouterModule.forRoot(appRoutes)
        // other imports here
      ],
      ...
    })
    export class AppModule { }
    

    searchComponent.ts

    import 'rxjs/add/operator/switchMap';
    import { OnInit } from '@angular/core';
    import { Router, ActivatedRoute, Params } from '@angular/router';
    
    export class SearchComponent implements OnInit {
    
    constructor(
       private route: ActivatedRoute,
       private router: Router
    ) {}
    ngOnInit() {
        this.route.params
          .switchMap((params: Params) => doSomething(params['tag']))
     }
    

    More infos:

    "Link Parameter Array" https://angular.io/docs/ts/latest/guide/router.html#!#link-parameters-array

    "Activated Route - the one stop shop for route info" https://angular.io/docs/ts/latest/guide/router.html#!#activated-route

    0 讨论(0)
  • 2020-11-27 04:20

    The simple way to do that in Angular 7+ is to:

    Define a path in your ?-routing.module.ts

    { path: '/yourpage', component: component-name }
    

    Import the ActivateRoute and Router module in your component and inject them in the constructor

    contructor(private route: ActivateRoute, private router: Router){ ... }
    

    Subscribe the ActivateRoute to the ngOnInit

    ngOnInit() {
    
        this.route.queryParams.subscribe(params => {
          console.log(params);
          // {page: '2' }
        })
    }
    

    Provide it to a link:

    <a [routerLink]="['/yourpage']" [queryParams]="{ page: 2 }">2</a>
    
    0 讨论(0)
  • 2020-11-27 04:22

    Angular2 v2.1.0 (stable):

    The ActivatedRoute provides an observable one can subscribe.

      constructor(
         private route: ActivatedRoute
      ) { }
    
      this.route.params.subscribe(params => {
         let value = params[key];
      });
    

    This triggers everytime the route gets updated, as well: /home/files/123 -> /home/files/321

    0 讨论(0)
  • 2020-11-27 04:23

    RouteParams are now deprecated , So here is how to do it in the new router.

    this.router.navigate(['/login'],{ queryParams: { token:'1234'}})
    

    And then in the login component you can take the parameter,

    constructor(private route: ActivatedRoute) {}
    ngOnInit() {
        // Capture the token  if available
        this.sessionId = this.route.queryParams['token']
    
    }
    

    Here is the documentation

    0 讨论(0)
  • 2020-11-27 04:24

    It seems that RouteParams no longer exists, and is replaced by ActivatedRoute. ActivatedRoute gives us access to the matrix URL notation Parameters. If we want to get Query string ? paramaters we need to use Router.RouterState. The traditional query string paramaters are persisted across routing, which may not be the desired result. Preserving the fragment is now optional in router 3.0.0-rc.1.

    import { Router, ActivatedRoute } from '@angular/router';
    @Component ({...})
    export class paramaterDemo {
      private queryParamaterValue: string;
      private matrixParamaterValue: string;
      private querySub: any;
      private matrixSub: any;
    
      constructor(private router: Router, private route: ActivatedRoute) { }
      ngOnInit() {
        this.router.routerState.snapshot.queryParams["queryParamaterName"];
        this.querySub = this.router.routerState.queryParams.subscribe(queryParams => 
          this.queryParamaterValue = queryParams["queryParameterName"];
        );
    
        this.route.snapshot.params["matrixParameterName"];
        this.route.params.subscribe(matrixParams =>
          this.matrixParamterValue = matrixParams["matrixParameterName"];
        );
      }
    
      ngOnDestroy() {
        if (this.querySub) {
          this.querySub.unsubscribe();
        }
        if (this.matrixSub) {
          this.matrixSub.unsubscribe();
        }
      }
    }
    

    We should be able to manipulate the ? notation upon navigation, as well as the ; notation, but I only gotten the matrix notation to work yet. The plnker that is attached to the latest router documentation shows it should look like this.

    let sessionId = 123456789;
    let navigationExtras = {
      queryParams: { 'session_id': sessionId },
      fragment: 'anchor'
    };
    
    // Navigate to the login page with extras
    this.router.navigate(['/login'], navigationExtras);
    
    0 讨论(0)
提交回复
热议问题