如何在Angular中获取活动的路由快照onpopstate事件

时间:2018-10-12 07:58:37

标签: javascript angular rxjs

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

  

此路线的当前快照

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

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();

1 个答案:

答案 0 :(得分:1)

snapshot没有给您更新的值。 ActivatedRoute具有queryParams的{​​{1}} BehaviourSubject,可以获取更新的subscribe

代替使用:

queryParams

使用:

this._activeRoute.snapshot.queryParams