根据 ActivatedRoute
接口(interface)文档 activeRoute.snapshot.queryParams
给出
The current snapshot of this route
但它给了我错误的结果,或者我在这里遗漏了一些东西。
window.location.hash
给出 => #url + ?page=1
和 window.location.search
给出一个空字符串。
const popStateEvent$ = fromEvent(window, 'popstate');
this.subscribePopStateEvent = popStateEvent$.subscribe(() => {
console.log(this._activeRoute.snapshot.queryParams);
callSomeFunctionHere(); // with exact query parameters
});
一个可能的解决方案是订阅;
const activeRouteSubscribe = this._activeRoute.queryParams.subscribe((params: any) => {});
然后取消订阅;
activeRouteSubscribe.unsubscribe();
令人惊讶的是,除非我进入 setTimeOut 函数,否则这也不起作用;
queryParamsEventHandler() {
setTimeout(() => {
this.queryParams = this.queryParamsFilterService.onPopState(this.queryParams);
callSomeFunctionHere();
}, 0);
}
我认为这不是一个好的解决方案,我正在寻求帮助以实现最佳实践并理解这个概念。在某些情况下,它也不调用 callSomeFunctionHere();
。
最佳答案
snapshot
不会为您提供更新后的值。 ActivatedRoute
有一个 queryParams
BehaviourSubject
可以订阅
,以获取更新的 queryParams
.
而不是使用:
this._activeRoute.snapshot.queryParams
使用:
this._activeRoute.queryParams.subscribe(...)
关于javascript - 如何在 Angular 中获取事件路由快照 onpopstate 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52774891/