Angular 2/4 How to get route parameters in app component?

前端 未结 3 472
一向
一向 2021-02-12 10:34

As I am new to angular 2/4 I am having trouble setting up a new application as per my need.

I am trying to build an application which will be called for from some anothe

3条回答
  •  执笔经年
    2021-02-12 11:09

    For one time value use like below:

    import { Router  , ActivatedRoute } from '@angular/router';
    
    constructor(private route: ActivatedRoute){}
    ngOnInit() {
        console.log(this.route.snapshot.params['username']);
    }
    

    The above snapshot method. Snapshot method just gives you result once you initiate the component. So this will keep on working if you change the route or destroy the component and initiate again only.

    A solution for the downvoters and/or anyone who want to update the param each time the route change will be:

    import { Router  , ActivatedRoute } from '@angular/router';
    
    constructor(private route: ActivatedRoute){}
    ngOnInit() {
        // Works first time only
        console.log(this.route.snapshot.params['username']);
        // For later use, updates everytime you change route
        this.route.params.subscribe((params) => {console.log(params['username'])});
    }
    

提交回复
热议问题