Search code examples
angularroutesangular-routing

Get data from URL in Angular 5


I enter a link in url bar.

http://localhost:4200/reset-password-action/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9/5

I want to get eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 and 5 from url.

I have it in my app-routing.module.ts file.

const routes: Routes = [
  { path: 'reset-password-action/:token/:user_id', component: NewPasswordComponent }
];

I need a simple syntax to get this data.


Solution

  • First of all Where do you want to get this data? If you want it in the same component, in your case I think it is NewPasswordComponent

    import {ActivatedRoute} from '@angular/router';
    import {OnInit, Component} from '@angular/core';
    
    @Component({...})
    export class NewPasswordComponent implements OnInit {
      constructor(private route: ActivatedRoute) {}
    
      ngOnInit() {
        console.log(this.route.snapshot.params.token);
        console.log(this.route.snapshot.params.user_id);
      } 
    }
    

    OR You can get like below also:

     constructor(private route: ActivatedRoute) {}
    
        ngOnInit() {
          this.route.params.subscribe(event => {
          this.token = event.token;
          this.user_id = event.user_id;
         });
        }