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

Location.go()、Router.navigate()和Router.navigateByUrl()用于将用户发送到Angular 2应用程序中的另一个部分(路由),但我不知道如何使用它们重定向到外部站点?


当前回答

在撕掉我的头之后,解决方案只是将http://添加到href。

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

其他回答

我认为你需要à target="_blank",这样你就可以使用window。开放:

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

在你的组件中

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;**

要使用@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>

在较新的Angular版本中,window为any

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

你可以使用这个-> window.location.href = '…';

这将改变页面到任何你想要的。