我制作了一个组件,并使用以下代码从 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/
相关文章:
asp.net-core-webapi - .NET Core 3 API - 在一个请求后停止工作
ios - 如何使用 SPM 和 Xcode11 将二进制文件与库链接
php - 如何修复 stripe-php 没有这样的 payment_method 错误
c# - 是否可以动态更改 ToolbarItem 的图标?
angular - graphql Angular 突变在控制台中显示 "Error: Networ
image - fluttercandies extended_image.如何用 1 根手指双击而
reactjs - 如何在更改层次结构后保持状态并防止重新渲染 react 组件?