正在运行业力测试时出现错误,无法读取null的属性'extras'

问题描述 投票:0回答:1

我制作了一个组件,正在使用以下代码从路由中获取一些数据。当我尝试ng测试时出现错误:

TypeError:无法读取null的属性'extras'

我应该在此组件的规格文件上导入什么以读取“状态”?在我的规格文件中,我添加了import { RouterTestingModule } from '@angular/router/testing',但仍然无法正常工作;

const navigation = this.router.getCurrentNavigation();
        const state = navigation.extras.state;
        console.log(state);
angular karma-runner
1个回答
0
投票
@Component({
  selector: 'app-root',
  template: `<pre>{{ state$ | async | json }}</pre>`,
})
export class AppComponent implements OnInit {
  private state$: Observable<object>;

  constructor(public router: Router) { }

  ngOnInit() {
    this.state$ =  this.router.events.pipe(
      filter(e => e instanceof NavigationStart),
      map(() => this.router.getCurrentNavigation().extras.state)
    )
  }
}

有关更多信息:Passing Data between Routes in Angular

© www.soinside.com 2019 - 2024. All rights reserved.