Zeeshan Malik
Zeeshan Malik

Reputation: 637

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.

Upvotes: 4

Views: 25343

Answers (3)

Abhishek
Abhishek

Reputation: 1778

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;
     });
    }

Upvotes: 9

Exterminator
Exterminator

Reputation: 1246

You need to import activated route first then use this

import {Router, ActivatedRoute} from '@angular/router';
class ABC {
    id: any;
    token: any;
    constructor(private activatedRoute: ActivatedRoute) {}
    ngOnInit() {
        this.activatedRoute.params.subscribe(params => {
            if (typeof params['id'] !== 'undefined') {
                this.id = params['id'];
            } else {
                this.id = '';
            }
            if (typeof params['token'] !== 'undefined') {
                this.id = params['token'];
            } else {
                this.id = '';
            }
        });
    }
}

Upvotes: 2

Aarsh
Aarsh

Reputation: 2595

You can get query params like this using ActivatedRoute. Here is the example::

import {Router, ActivatedRoute, Params} from '@angular/router';
import {OnInit, Component} from '@angular/core';

@Component({...})
export class MyComponent implements OnInit {
 queryParamsStatus ='';

  constructor(private activatedRoute: ActivatedRoute) {}

  ngOnInit() {
    // subscribe to router event
    this.activatedRoute.params.subscribe((params: Params) => {
        this.queryParamsStatus= params['status'];
        console.log(queryParamsStatus );

      });
    let tempRows = this.rows.filter(s => s.staus === this.queryParamsStatus);
  }

}

You can get token/userId by simply replacing status by token or userid.

Hope this will work.

Upvotes: 0

Related Questions