Reputation: 125
I want to get the id from the url and then use that to navigate to a different specific view I have the following function
getStudent(): void {
const id = + this.route.snapshot.paramMap.get('id');
this.studentService.getStudent(id)
.subscribe(student => this.SpecificStudent = student);
I have tried to make sure it is not null by using the assertion
// !
const id = + this.route.snapshot.paramMap.get('id')!;
If I do this, it doesn’t show an error, but alert(id) gives 0 which is wrong
Upvotes: 5
Views: 8321
Reputation: 81
You can do something like this
id: number;
ngOnInit(){
this.route.paramMap.subscribe(params =>{
const id = params.get('id');
this.id = Number(id);
});
Upvotes: 0
Reputation: 630
you can do it as
const id = + this.route.snapshot.paramMap.get('id');
id && this.studentService.getStudent(id)
.subscribe(student => this.SpecificStudent = student);
Upvotes: 1
Reputation: 442
You can use the Number
method:
Number(this.route.snapshot.paramMap.get('id'))
Or
this.route.paramMap.subscribe(param => {
let id = +param.get('id');
})
Upvotes: 12
Reputation: 1679
You have two possible solutions:
const id = this.route.snapshot.paramMap.get('id') || 'yourDefaultString';
this.studentService.getStudent(id)
.subscribe(student => this.SpecificStudent = student);
const id = this.route.snapshot.paramMap.get('id');
this.studentService.getStudent(id ? id : 'yourDefaultString')
.subscribe(student => this.SpecificStudent = student);
Upvotes: 2