如何在Angular2中重定向到外部URL?

294

在Angular 2中,将用户重定向到完全外部的URL的方法是什么?例如,如果我需要重定向用户到OAuth2服务器以进行身份验证,我该如何做?

Location.go()Router.navigate()Router.navigateByUrl()可以用于将用户发送到Angular 2应用程序中的另一个部分(路由),但我看不出它们如何用于重定向到外部网站?


10
注意:如果您的外部URL不包含http://或https://,Angular 4将把该URL视为内部路由。以防其他人遇到同样的问题。 - aherocalledFrog
哇,这个线程太有趣了。想象一下解释Angular的好处,然后再解释如何导航到外部URL。预计需要1小时的努力。 - AlxVallejo
16个回答

5

我使用了window.location.href='http://external-url';

对我来说,在Chrome中重定向有效,但在Firefox中无效。 以下代码解决了我的问题:

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

2
没有上述的解决方案对我有用,我只是添加了

。翻译后为:

以上解决方案都不适用于我,我只需添加

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

This worked for me.

Or try using

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

你尝试过使用 window.open(url, "_self") 吗? 我认为你因为使用了模块而导致当前 URL 被覆盖的问题。 - Rejja Kubzek

1
大部分目前的回复都是最佳的,但为了更清晰的代码,我建议使用window而不是注入document的引用,因为它本质上只是window本身的重复引用。唯一需要使用它的情况是当你无法直接使用window时。
const url : string = "https://dev59.com/iFsX5IYBdhLWcg3wAbi6" 
window.open(url, "_blank")
//window.open(url, "_self")
//window.open(url, "_parent")
//window.open(url, "_top")

这段代码将打开一个窗口,其第二个参数是target atribute,它决定了URL将在哪里打开。
具体的目标属性值如下:(mozilla)
_self:当前浏览上下文。(默认)
_blank:通常是新标签页,但用户可以配置浏览器以打开新窗口。
_parent:当前浏览上下文的父级浏览上下文。如果没有父级,则行为与_self相同。
_top:最顶层的浏览上下文(当前上下文的祖先中的“最高”上下文)。如果没有祖先,则行为与_self相同。
通过这样做,您可以更清晰地确定新URL应该在哪里打开,以提供最佳的用户体验。
无论如何,您都可以用router.navigate替换。
window.open("relativePathFromCurentURL","_self") 

通过您的网站导航。我只能推荐您在某些组件不需要导入路由的情况下使用此方法。

0

要使用 @Inject,您必须导入它。我在任何答案中都没有看到这一点。

TS 文件:

import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Component({
  selector: 'app-my-comp.page',
  templateUrl: './my-comp.page.component.html',
  styleUrls: ['./my-comp.page.component.scss']
})
export class MyCompPageComponent {

  constructor(
    @Inject(DOCUMENT) private document: Document
  ) { }

  goToUrl(): void {
    this.document.location.href = 'https://google.com/';
  }

}

HTML文件:

<button type="button" (click)="goToUrl()">Google</button>

-1
在你的 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';
  }
}

在你的 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;**

-2

就这么简单

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

2
这在过去的多年中已经说过多次了。 - Michael Oryl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接