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

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


当前回答

就像这样简单

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

其他回答

我使用的是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');
  }
}

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

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

正如丹尼斯·斯莫雷克所说,解决办法非常简单。将window.location.href设置为你想要切换到的URL,它就可以工作了。

例如,如果你在组件的类文件(控制器)中有这个方法:

goCNN() {
    window.location.href='http://www.cnn.com/';
}

然后你可以很简单地在模板中的一个按钮(或任何东西)上调用它:

<button (click)="goCNN()">Go to CNN</button>

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

如果你一直在使用OnDestry生命周期钩子,你可能有兴趣在调用window.location.href=…

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

这会在你的组件中触发OnDestry回调。

哦,还有:

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

是找到路由器的地方。

——编辑 遗憾的是,我在上面的例子中可能错了。至少现在在我的生产代码中没有像预期的那样工作-所以,直到我有时间进一步调查,我这样解决它(因为我的应用程序真的需要钩子时可能)

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

基本上路由到任何(虚拟)路由来强制钩子,然后按照请求导航。