Get data from URL in Angular 5
15,660
Solution 1
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;
});
}
Solution 2
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 = '';
}
});
}
}
Author by
Zeeshan Malik
Updated on December 05, 2022Comments
-
Zeeshan Malik over 1 year
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.
-
Kirk Larkin over 5 yearsWhere do you want to get this data?
-
Zeeshan Malik over 5 yearsfor now in the current component NewPasswordComponent
-
AT82 over 5 yearsHave you read the documentation? angular.io/tutorial/toh-pt5#extract-the-id-route-parameter
-