Search code examples
angulartypescriptangular2-routingangular7angular-routing

Page redirecting when clicking on blank space on angular 2


I want to redirect to another page when I get some response from the server. (This process is too slow, and take almost 60 seconds to get the response from server). Meanwhile, I will show some spinner kind of thing, And when I get the response, I will redirect to another page. Looks simple?

Yes, But the problem is, Page is not getting redirected automatically when I get the response. It stays on the same page, Now, If I click anywhere on the page, It redirected to another page, Little weird situation.

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. 
          }
        });
      });

Is this situation, because, we are getting a response from the second service after 60 seconds. This is a little weird scenario, but it is happening. Is this 60 second the villain.


Solution

  • This solve my issue finally.

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

    Problem was, Router Navigate does not activate onInit after external request. The second subscription was using the external request for notification.

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