简体   繁体   中英

Angular 9 : Unable to redirect to a specific route in angular app after redirecting from an external url

I have an angular app that is using version 9. From one of my routes(say, /search/details/id ), I am redirecting to an external URL using the URL value I received from API response like

window.location.href = "https://www.payment.com";

Now I am getting redirected to the external payment page where I can make the payment or cancel the transaction.

If I click cancel I am redirected back to the previous page which is my angular app with route /search/details/:id . From here, if I click the browser back button, I am taken to the payment page at https://www.payment.com . I want to get navigated to the angular app /search route instead from which I initially navigated to /search/details/id.

I tried to handle the browser back button in the component in the following ways,

1. fromEvent(window, 'popstate')
      .subscribe((e) => {
        console.log(e, 'back button');
        this.router.navigate(
          ['/search']);
   });
   Added inside the constructor of the component corresponding to /search/details/:id

2. router.events.forEach((event) => {
      if(event instanceof NavigationStart) {
        if (event.navigationTrigger === 'popstate') {
          console.log(event, 'back button router');
        }
      }
    });
    Added inside constructor
3. @HostListener('window:popstate', ['$event'])
  onPopState(event) {
    this.router.navigate(
        ['search/']);
  }
  Inside the component

None of the above callbacks get triggered when I come back from the external page and click the browser back button from the/search/details/:id page. However, when I click on the browser back button from /search/details/id page without going to the external page, the above callbacks are getting triggered and it's taken to /search page.

So I think reloading the angular app after redirecting from the external prevents the popstate event to get triggered.

Any thoughts/solution is highly appreciated.

Thanks

when you do window.location.href = "https://www.payment.com"; you close the current app and open new app (the one provided by payment.com).

I think a good way to do what you have to do is create a new component with an iframe inside and open it as modal or popup. Probably you hav to use DomSanitizer to sanitize url for XSS risk

in your constructor in page /search/details/id add these two line:

history.pushState(null, '', 'http://localhost:4200/search');
history.pushState(null, '', 'http://localhost:4200/search/details/id');

or in production:

history.pushState(null, '', 'https://your_domain/search');
history.pushState(null, '', 'https://your_domain/search/details/id');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM