Object is possibly Null

Viewed 5578

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

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

You have two possible solutions:

  1. Assign to id if not falsy, otherwise assign something else:
const id = this.route.snapshot.paramMap.get('id') || 'yourDefaultString';
this.studentService.getStudent(id)
.subscribe(student => this.SpecificStudent = student);
  1. check before passing the argument to the function that is not falsy, if it's falsy we will pass our default string:
const id = this.route.snapshot.paramMap.get('id');
this.studentService.getStudent(id ? id : 'yourDefaultString')
.subscribe(student => this.SpecificStudent = student);

you can do it as

const id = + this.route.snapshot.paramMap.get('id');
id && this.studentService.getStudent(id)
     .subscribe(student => this.SpecificStudent = student);
Related