单击 angular 上的空白 space 时页面重定向 2

Page redirecting when clicking on blank space on angular 2

我想在收到服务器响应时重定向到另一个页面。 (这个过程太慢了,几乎需要 60 秒才能得到服务器的响应)。同时,我会展示一些微调器之类的东西,当我得到响应时,我会重定向到另一个页面。看起来很简单?

是的,但问题是,当我收到响应时,页面没有自动重定向。它停留在同一个页面上,现在,如果我点击页面上的任何地方,它会重定向到另一个页面,有点奇怪的情况。

this.optimizationService
      .runOptimization(this.runOptimizationModel)
      .subscribe(optimizationResult => {  // this is the first service which send request to server.

        this.optimizationService.notificationEvent.subscribe(eventData => {
          console.log(eventData); // this is another external service for notifications in which, when I will get the response, I want to redirect to another page. 
          if (eventData && eventData.length) {
            this._router.navigate([this.optimizationResultScreenURL, 'e1517589-905e-485b-b7ee-7bc6521dcc93']); // This is url rerouting. If I cut and paste this line after first service subscription, it is working fine. 
          }
        });
      });

是这种情况吗,因为,我们在60秒后得到了第二个服务的响应。这是一个有点奇怪的场景,但它正在发生。 这60秒是不是反派.

你能按照这些思路尝试一下吗? (多个嵌套订阅不是一个好习惯)

this.optimizationService
      .runOptimization(this.runOptimizationModel)
      .pipe(
            switchMap(optiResult => this.optimizationService.notificationEvent),
            filter(eventData => eventData && eventData.length),
            tap(eventData => this._router.navigate(/* extract URL data here */))
      )
      .subscribe();

我不完全清楚第一个请求做了什么,或者你在哪里使用它的响应,但我的回答中的理论是使用 RxJS 操作符来控制流程。希望这有用。

这终于解决了我的问题。

return this.zone.run(() => this.router.navigate(['/path/to/route']));

问题是,路由器导航在外部请求后没有激活 onInit。第二个订阅使用外部请求进行通知。

参考:https://github.com/angular/angular/issues/20112#issuecomment-398060545