0

When a service in our Angular app performs a HTTP request, we want to direct a user to the login page.

Here's our setup:

Here's what we're trying:

@Injectable({
    providedIn: 'root'
})
export class ServiceHelper {
    constructor(private router: Router) {}

    public handleError<T>(result?: T): (error: any) => Observable<T> {
        {
            return (error: HttpErrorResponse): Observable<T> => {
                if (error.status === 401) {
                    // Direct the user to login
                    this.router.navigate(['/login']);
                }
                console.error(error);
                return of(result as T);
            };
        }
    }
}

The problem is that on 401, the browser gets directed to https://foo.bar/ui/login. We run the app with 'base-href=/ui' in our angular.json. Our login app is a different system, outside that base-href.

Is there any good way to tell Angular's router to redirect the user at an absolute URL on the same server, outside the base-href?

Thanks!

Cuga
  • 17,668
  • 31
  • 111
  • 166
  • 2
    I think the `router` is for internal routes only. To navigate to an external route from the app, I would use the `Window` object. https://stackoverflow.com/a/1226718/7365461 – AliF50 Mar 01 '21 at 20:25
  • 1
    @AliF50 I think you're right. I could get the browser's address bar to show the right URL by trying ```this.router.navigateByUrl('/../login');```. But even that wouldn't work, seemingly b/c it was an external route. `window.location.href = '/../login'` seems to work. If you write an answer, I'll accept it – Cuga Mar 01 '21 at 22:16

2 Answers2

2

The Angular router is only for internal routes of the application. To navigate to an external route from the app, I would use the Window object. Check it out here

AliF50
  • 16,947
  • 1
  • 21
  • 37
  • 1
    This solved my issue by using `window.location.href = '/../login';` instead of the `router` service. Note the `/../` which let me traverse up a directory. – Cuga Mar 02 '21 at 15:05
-1

use HTTP interceptor and intercept the URL in the request object. If the URL contains "login" as a substring, replace the URL with https://foo.bar/login.

This could be helpful

b_hunter
  • 9
  • 1