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

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


当前回答

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

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';
}

其他回答

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

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';
}

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

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

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

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

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

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

这对我很管用。

或者试着使用

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

如果你一直在使用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/';});

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