javascript - 如何在 Angular 中获取事件路由快照 onpopstate 事件

标签 javascript angular rxjs

根据 ActivatedRoute 接口(interface)文档 activeRoute.snapshot.queryParams 给出

The current snapshot of this route

但它给了我错误的结果,或者我在这里遗漏了一些东西。

window.location.hash 给出 => #url + ?page=1window.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/

相关文章:

javascript - 为什么使用 NGRX 而不是构造函数注入(inject)服务?

javascript - 使用 bootstrap 4 在 html 中的另一个图像上叠加图像

javascript - 从 AJAX 请求返回 while 循环

angular - 无法使用 *ngFor 上的错误读取未定义的属性 'toUpperCase'

angular - 如何在 Angular2 中进行嵌套的 Observable 调用

angular - 从 Angular 服务通过管道传输时,rxjs catchError 不起作用

javascript - 打破 iframe 中的父级、顶级变量以防止框架破坏,但仍然访问父级的功能

javascript - 如何为除具有特定类的所有元素添加事件?

angular - @angular/flex-layout 如何 : different class based on screensize?

javascript - Typemoq 和 Angular-cli 不能一起工作