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

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


当前回答

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

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

其他回答

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

对我来说,重定向在Chrome中有效,但在Firefox中不起作用。 下面的代码解决了我的问题:

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

使用前面描述的方法的Angular方法是从@angular/common(或Angular中的@angular/platform-browser)导入DOCUMENT < 4)和使用

document.location.href = 'https://stackoverflow.com';

在函数内部。

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>

查看platformBrowser repo以获得更多信息。

以上的解决方案对我都不起作用,我只是补充说

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

这对我很管用。

或者试着使用

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

你可以用多种方式重定向:

like

window.location.href = 'redirect_url';

Angular文档的另一种方式:

从angular导入文档,文档必须被注入,否则你会得到错误

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

在你的组件中

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