How to handle query parameters in angular 2

后端 未结 12 772
灰色年华
灰色年华 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:10

    Angular 4:

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

    .html

    A link
    

    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

提交回复
热议问题