How to handle query parameters in angular 2

后端 未结 12 773
灰色年华
灰色年华 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: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);
    

提交回复
热议问题