在Angular 2中,将用户重定向到完全外部的URL的方法是什么?例如,如果我需要重定向用户到OAuth2服务器以进行身份验证,我该如何做?
Location.go()
、Router.navigate()
和Router.navigateByUrl()
可以用于将用户发送到Angular 2应用程序中的另一个部分(路由),但我看不出它们如何用于重定向到外部网站?
在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');
以上解决方案都不适用于我,我只需添加
即可。window.location.href = "www.google.com"
event.preventDefault();
This worked for me.
Or try using
window.location.replace("www.google.com");
const url : string = "https://dev59.com/iFsX5IYBdhLWcg3wAbi6"
window.open(url, "_blank")
//window.open(url, "_self")
//window.open(url, "_parent")
//window.open(url, "_top")
window.open("relativePathFromCurentURL","_self")
要使用 @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>
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';
}
}
<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='http://www.google.com/';