我制作了一个组件,正在使用以下代码从路由中获取一些数据。当我尝试ng测试时出现错误:
TypeError:无法读取null的属性'extras'
我应该在此组件的规格文件上导入什么以读取“状态”?在我的规格文件中,我添加了import { RouterTestingModule } from '@angular/router/testing'
,但仍然无法正常工作;
const navigation = this.router.getCurrentNavigation();
const state = navigation.extras.state;
console.log(state);
@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)
)
}
}