【问题标题】:ERROR TypeError: Cannot read property 'extras' of null错误类型错误:无法读取 null 的属性“附加”
【发布时间】:2020-09-05 14:43:45
【问题描述】:

这是我的代码,我收到错误“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
    };
  }

【问题讨论】:

标签: angular


【解决方案1】:

您可能需要在构造函数中调用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() {
  }
}

【讨论】:

  • 如果我将 this.router.getCurrentNavigation().navigation.extras.state 设置为 Hotel 那么我如何将值传递给 reqObj
  • 因为变量reqObj也被定义为Hotel类型。请注意reqObj: Hotel;这一行。
【解决方案2】:

您是否在构造函数中包含了正确的路由器?喜欢:

import { Router } from '@angular/router';

constructor(public router: Router)
{
    const navigation = router.getCurrentNavigation();
}

【讨论】:

    【解决方案3】:

    如果state[routerLink] 一起使用,则会被忽略... (Angular - Issue with routerLink and state)

    【讨论】:

      猜你喜欢
      • 2021-12-03
      • 2017-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多