在Angular 2中将用户重定向到完全外部URL的方法是什么。例如,如果我需要将用户重定向到OAuth2服务器以进行身份验证,我该怎么做?
Location.go()
,Router.navigate()
和Router.navigateByUrl()
可以将用户发送到Angular 2应用程序中的另一个部分(路线),但我看不出它们如何用于重定向到外部网站?
你可以使用这个 - > window.location.href = '...';
这会将页面更改为您想要的任何内容..
在你的component.ts中
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;**
我刚刚补充说,上述解决方案都不适用于我
window.location.href = "www.google.com"
event.preventDefault();
这对我有用。
前面描述的方法的Angular方法是从DOCUMENT
(或Angular <4中的@angular/common
)导入@angular/platform-browser
并使用
document.location.href = 'https://stackoverflow.com';
在一个函数内部。
一些-page.component.ts
import { DOCUMENT } from '@angular/common';
...
constructor(@Inject(DOCUMENT) private document: any) { }
goToUrl(): void {
this.document.location.href = 'https://stackoverflow.com';
}
一些-page.component.html
<button type="button" (click)="goToUrl()">Click me!</button>
查看plateformBrowser repo了解更多信息。
正如丹尼斯斯莫勒克所说,The solution死得很简单。将window.location.href
设置为您要切换到的URL,它就可以正常工作。
例如,如果组件的类文件(控制器)中有此方法:
goCNN() {
window.location.href='http://www.cnn.com/';
}
然后你可以通过在模板中的按钮(或其他)上调用适当的(click)
来简单地调用它:
<button (click)="goCNN()">Go to CNN</button>
我认为你需要àtarget=“_ blank”,那么你可以使用window.open
:
gotoGoogle() : void {
window.open("https://www.google.com", "_blank");
}
如果你一直在使用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/';});
基本上路由到任何(虚拟)路由以强制挂钩,然后按要求导航。
在较新版本的Angular中,窗口为any
(window as any).open(someUrl, "_blank");
我用了window.location.href ='http://external-url';
对我来说,重定向在Chrome中有效,但在Firefox中不起作用。以下代码解决了我的问题:
window.location.assign('http://external-url');
在解开头之后,解决方案就是将http://添加到href。
<a href="http://www.URL.com">Go somewhere</a>
我使用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');
}
}