错误类型错误:无法读取 null 的属性“额外”

swe*_*tha 3 angular

这是我的代码,我收到错误“ERROR TypeError: Cannot read property 'extras' of null ”

  ngOnInit() {
  const navigation = this.router.getCurrentNavigation();
  const state = navigation.extras.state as {
  api: string;
  trace_id: string;
  token_id: string;
  hotel_code: string;
  result_index: string;
  };
  this.reqObj = {
  api: state.api,
  trace_id: state.trace_id,
  token_id: state.token_id,
  hotel_code: state.hotel_code,
  result_index: state.result_index
    };
  }
Run Code Online (Sandbox Code Playgroud)

Mic*_*l D 5

getCurrentNavigation()您可能需要在构造函数中调用。您还可以定义一个接口以避免重复对象类型。尝试以下操作

export interface Hotel {
  api: string;
  trace_id: string;
  token_id: string;
  hotel_code: string;
  result_index: string;
}

@Component({
  selector: 'my-details',
  templateUrl: './details.component.html',
  styleUrls: [ './details.component.css' ]
})
export class DetailsComponent implements OnInit {
  reqObj: Hotel;

  constructor(private router: Router) {
    this.reqObj = this.router.getCurrentNavigation().navigation.extras.state as Hotel;
  }

  ngOnInit() {
  }
}
Run Code Online (Sandbox Code Playgroud)