How to redirect to an external URL in Angular2?
What is the method for redirecting the user to a completely external URL in Angular 2. For example, if I need to redirect the user to an OAuth2 server in order to authenticate, how would I do that?
Location.go()
, Router.navigate()
, and Router.navigateByUrl()
are fine for sending the user to another section (route) within the Angular 2 app, but I can't see how they could be used to redirect to an external site?
Solution 1:
You can use this-> window.location.href = '...';
This would change the page to whatever you want..
Solution 2:
An Angular approach to the methods previously described is to import DOCUMENT
from @angular/common
(or @angular/platform-browser
in Angular
< 4) and use
document.location.href = 'https://stackoverflow.com';
inside a function.
some-page.component.ts
import { DOCUMENT } from '@angular/common';
...
constructor(@Inject(DOCUMENT) private document: Document) { }
goToUrl(): void {
this.document.location.href = 'https://stackoverflow.com';
}
some-page.component.html
<button type="button" (click)="goToUrl()">Click me!</button>
Check out the platformBrowser repo for more info.
Solution 3:
The solution, as Dennis Smolek said, is dead simple. Set window.location.href
to the URL you want to switch to and it just works.
For example, if you had this method in your component's class file (controller):
goCNN() {
window.location.href='http://www.cnn.com/';
}
Then you could call it quite simply with the appropriate (click)
call on a button (or whatever) in your template:
<button (click)="goCNN()">Go to CNN</button>