gpt4 book ai didi

angular - 运行 karma 测试时出现错误无法读取 null 的属性 'extras'

转载 作者:行者123 更新时间:2023-12-05 07:18:26 24 4
gpt4 key购买 nike

我制作了一个组件,并使用以下代码从 route 获取一些数据。当我尝试 ng test 时出现错误:

TypeError: Cannot read property 'extras' of null

我应该在此组件的规范文件中导入什么来读取“状态”?在我的规范文件中,我添加了 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)
)
}
}

更多信息:Passing Data between Routes in Angular

关于angular - 运行 karma 测试时出现错误无法读取 null 的属性 'extras',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58267153/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com