ChatGPT解决这个技术问题 Extra ChatGPT

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?

Don't you find it ridiculous that this is not easily done? There has to be a simpler way to do this, without having to code for it.
Note: If your external URL doesn't contain http:// or https://, Angular 4 will treat the URL as an internal route. In case anyone else is struggling with that.
@aherocalledFrog your comment saved my day. thx!

Z
Zoe stands with Ukraine

You can use this-> window.location.href = '...';

This would change the page to whatever you want..


Ugh, I tried calling it as a function for some reason rather than just changing the value. Setting the value directly works.
Just remember that directly referencing the window will limit your code to platforms with a window object.
@ender isn't there an alternative to it? There might be scenarios where we genuinely want to redirect to external links. Sure, we can use window.location.href, but like you say, it has its disadvantages. If there is a supported API in Angular, that would help better.
Sure, but that is 99% of all platforms that run javascript and need to do a page redirect. Even phantom/casperJs respect the window object. You can call document.location.href or even Location.href as they all refer to the same object. Location Reference
@DennisSmolek But if you try to compile this into an android app using Universal, wouldn't this behavior fail?
O
Ollie

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.


Would the target site know that the request is coming from our app, since the requirement here is to redirect for login purpose and hence the SSO app should redirect back to our app after success
In angular 4, DOCUMENT should be imported from @angular/common (i.e. import { DOCUMENT } from '@angular/common';), but otherwise this works great! See github.com/angular/angular/blob/master/packages/…
what is the purpose of injecting document this way @Inject(DOCUMENT) private document: any
@SunilGarg Injecting DOCUMENT makes it easier to replace the document object with a mock in unit tests. It also allows for an alternative implementation to be used on other platforms (server/mobile).
For strict typing I use, constructor(@Inject(DOCUMENT) private document: Document) { }
C
Community

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>

J
JustLearning

I think you need à target="_blank", so then you can use window.open :

gotoGoogle() : void {
     window.open("https://www.google.com", "_blank");
}

H
Henry Arousell

If you've been using the OnDestry lifecycle hook, you might be interested in using something like this before calling window.location.href=...

    this.router.ngOnDestroy();
    window.location.href = 'http://www.cnn.com/';

that will trigger the OnDestry callback in your component that you might like.

Ohh, and also:

import { Router } from '@angular/router';

is where you find the router.

---EDIT--- Sadly, I might have been wrong in the example above. At least it's not working as exepected in my production code right now - so, until I have time to investigate further, I solve it like this (since my app really need the hook when possible)

this.router.navigate(["/"]).then(result=>{window.location.href = 'http://www.cnn.com/';});

Basically routing to any (dummy) route to force the hook, and then navigate as requested.


Thanks a lot for this solution. I was searching for some time for a solution and managed only to open an external link on a new tab, but on same tab all the window.open, location.pathname/href.... didn't let me to navigate away from my site. This is the most clean and correct way to handle routing out of the angular app!
W
WizardsOfWor

in newer versions of Angular with window as an any

(window as any).open(someUrl, "_blank");

the best answer
Do newer versions on Angular not allow just plain window?
J
Joel

After ripping my head off, the solution is just to add http:// to href.

<a href="http://www.URL.com">Go somewhere</a>

What question do you answer with that?
@GuidoFlohr I have a form where people have to put a link, and sometimes they put 'www.someLink.com' , and in this case the redirection is broken, due to the missing 'http' before. So this answer is correct.
@Nitneq The question is about redirecting in angular. And the answer has zero to do with the question.
@GuidoFlohr sometimes, Angular is not the problem.
n
naveen

I used window.location.href='http://external-url';

For me the the redirects worked in Chrome, but didn't work in Firefox. The following code resolved my problem:

window.location.assign('http://external-url');

u
user3220080

I did it using Angular 2 Location since I didn't want to manipulate the global window object myself.

https://angular.io/docs/ts/latest/api/common/index/Location-class.html#!#prepareExternalUrl-anchor

It can be done like this:

import {Component} from '@angular/core';
import {Location} from '@angular/common';
@Component({selector: 'app-component'})
class AppCmp {
  constructor(location: Location) {
    location.go('/foo');
  }
}

For me, this just changes the URL and the app state doesn't change (actual route looks the same). Even 'location.replaceState('/') did not act as I expected. router.navigate(['/']); is what did it for me.
Angular 2 Location doesn't sound applicable. The docs state that the purpose of location is: "Location is responsible for normalizing the URL against the application's base href." Using this to redirect to a URL within the application may be appropriate; using it to redirect to an external URL doesn't seem to fit with docs.
S
Siraj Ali

You can redirect with multiple ways:

like

window.location.href = 'redirect_url';

another way Angular document:

import document from angular and the document must be inject as well as bellow otherwise you will get error

import { DOCUMENT  } from '@angular/common';
export class AppComponent {
     constructor(
       @Inject(DOCUMENT) private document: Document
    ) {}
   this.document.location.href = 'redirect_url';
}

s
sravan ganji

There are 2 options:

if you want to redirect in same window/tab gotoExternalDomain(){ window.location.href='http://google.com/' } if you want to redirect in new tab gotoExternalDomain(){ (window as any).open("http://google.com/", "_blank"); }


Hi! Can you explain what's "_blank" for since link is opened in new tab without it as well?
@tz0 It opens an URL in a new tab.
@Coti but it opened that url without "_blank" as well
R
Rishi0405

None of the above solutions worked for me, I just added

window.location.href = "www.google.com"
event.preventDefault();

This worked for me.

Or try using

window.location.replace("www.google.com");

L
Linh

In your component.ts

import { Component } from '@angular/core';

@Component({
  ...
})
export class AppComponent {
  ...
  goToSpecificUrl(url): void {
    window.location.href=url;
  }

  gotoGoogle() : void {
    window.location.href='https://www.google.com';
  }
}

In your component.html

<button type="button" (click)="goToSpecificUrl('http://stackoverflow.com/')">Open URL</button>
<button type="button" (click)="gotoGoogle()">Open Google</button>

<li *ngFor="item of itemList" (click)="goToSpecificUrl(item.link)"> // (click) don't enable pointer when we hover so we should enable it by using css like: **cursor: pointer;**

A
Akitha_MJ

Just simple as this

window.location.href='http://www.google.com/';

This has already been said multiple times in years past.