2

I have a web app that was partly migrated from PHP and angular-js to angular(currently v13) after a successful login, there's a redirection to other pages. since my login page is angular-based, I'd like to use angular routing to redirect to pages that are angular-based and are working under the router-outlet. And redirect using window.location for old pages (e.g PHP).

The url to redirect to is dynamic. Is there a way that I can determine if the url is part of the angular application and can be navigated to using the router?

3
  • 1
    If all your routing is consistently done with Angular directives or API, then any page matching your routes will load the corresponding component into router-outlet. Now if you have a fallback 404 page for all remaining URLs, then in this 404 page you can redirect to your old pages utilizing window.location. Commented Jul 14, 2022 at 16:39
  • @Benny so you suggest having an empty 404 component that will just redirect using window.location? Commented Jul 14, 2022 at 16:42
  • Yes. Maybe @Anton's answer below is more elegant Commented Jul 14, 2022 at 16:44

1 Answer 1

2

You can use router events for that. Do this code in a service or your root navigation component:

constructor(private router: Router) {
    router.events.pipe(
      filter(event => event instanceof NavigationError),
      takeUntil(this.destroy),
    ).subscribe(.. here you should redirect with window.location);
  }

Also if you needn't error in the console, just provide custom error handler in providers:

providers: [{
    provide: ErrorHandler,
    useClass: CustomErrorHandler,
}],

And one last moment: you have to remove '**' path parsing from your root routes in RouterModule.

Sign up to request clarification or add additional context in comments.

4 Comments

looks good, I'll try it :) what is this.destroy?
Just the Subject, emits value and completes in OnDestroy hook. Recommend to use in any subscriptions :)
Marineko I've used your solution and it's working well, the thing is that now if a client use the url bar to change the url to an angular component and have a mistake I can't redirect him to a not found page and he just gets redirected infinitely. is there any way to avoid this scenario?
@Daniel you have to listen browser api for that. Make @HostListener('window:beforeunload') with function to check.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.