Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object is possibly Null

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

like image 351
Ojage S Avatar asked Dec 18 '22 11:12

Ojage S


1 Answers

You can use the Number method:

Number(this.route.snapshot.paramMap.get('id'))

Or

this.route.paramMap.subscribe(param => {
      let id = +param.get('id');
})
like image 102
Bayram Eren Avatar answered Dec 23 '22 18:12

Bayram Eren