对象可能为Null

我想从 url 中获取 id,然后使用它导航到不同的特定视图我有以下功能

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

我试图通过使用断言来确保它不为空

// !

const id = + this.route.snapshot.paramMap.get('id')!;

如果我这样做,它不会显示错误,但 alert(id) 给出 0,这是错误的

回答

您可以使用以下Number方法:

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

或者

this.route.paramMap.subscribe(param => {
      let id = +param.get('id');
})


以上是对象可能为Null的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>