0
votes

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!

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. stackoverflow.com/a/1226718/7365461 - AliF50
@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

2 Answers

1
votes

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

-1
votes

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