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

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


当前回答

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

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

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

其他回答

有两种选择:

如果你想重定向在同一窗口/标签 gotoExternalDomain () { window.location.href = ' http://google.com/ ' } 如果你想重定向到新标签 gotoExternalDomain () { (窗口).open(“http://google.com/”、“平等”); }

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

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

我使用的是Angular 2 Location,因为我不想自己操作全局窗口对象。

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

可以这样做:

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

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

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

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

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

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