Angular2에서 외부 URL로 리디렉션하는 방법은 무엇입니까?
Angular 2에서 사용자를 완전히 외부 URL로 리디렉션하는 방법은 무엇입니까?예를 들어 인증을 위해 사용자를 OAuth2 서버로 리디렉션해야 하는 경우 어떻게 해야 합니까?
Location.go(),Router.navigate(),그리고.Router.navigateByUrl()Angular 2 앱 내의 다른 섹션(경로)으로 사용자를 보내는 것은 괜찮지만, 외부 사이트로 리디렉션하는 데 어떻게 사용할 수 있는지 알 수 없습니다.
이것을 사용할 수 있습니다->window.location.href = '...';
이렇게 하면 페이지가 원하는 대로 변경됩니다.
앞에서 설명한 방법에 대한 Angular 접근 방식은 다음과 같습니다.DOCUMENT부터@angular/common(또는)@angular/platform-browser각도 < 4) 및 사용
document.location.href = 'https://stackoverflow.com';
함수 내부에
some-page.component.ts
import { DOCUMENT } from '@angular/common';
...
constructor(@Inject(DOCUMENT) private document: Document) { }
goToUrl(): void {
this.document.location.href = 'https://stackoverflow.com';
}
some-page.component.sys
<button type="button" (click)="goToUrl()">Click me!</button>
자세한 내용은 브라우저 보고서 플랫폼을 확인하십시오.
Dennis Smolek가 말했듯이 해결책은 매우 간단합니다.세트window.location.href전환하려는 URL로 이동하면 바로 작동합니다.
예를 들어 구성 요소의 클래스 파일(컨트롤러)에 이 방법이 있는 경우:
goCNN() {
window.location.href='http://www.cnn.com/';
}
그러면 당신은 그것을 적절한 것으로 아주 간단하게 부를 수 있습니다.(click)템플릿의 단추(또는 원하는 대로)를 호출합니다.
<button (click)="goCNN()">Go to CNN</button>
제 생각에 당신은 a 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';
라우터를 찾을 수 있습니다.
---EDIT--- 슬프게도 위의 예에서 제가 틀렸을 수도 있습니다.적어도 지금은 생산 코드에서 예상한 대로 작동하지 않습니다. 그래서 더 자세히 조사할 시간이 있을 때까지 이렇게 해결합니다(가능하면 내 앱에 후크가 정말 필요하기 때문입니다).
this.router.navigate(["/"]).then(result=>{window.location.href = 'http://www.cnn.com/';});
기본적으로 임의의 (더미) 경로로 라우팅하여 후크를 강제로 연결한 다음 요청에 따라 탐색합니다.
창이 있는 Angular의 최신 버전에서any
(window as any).open(someUrl, "_blank");
두 가지 옵션이 있습니다.
동일한 창/탭에서 리디렉션하려는 경우
gotoExternalDomain(){ window.location.href='http://google.com/' }새 탭에서 리디렉션하려는 경우
gotoExternalDomain(){ (window as any).open("http://google.com/", "_blank"); }
제 머리를 쥐어뜯은 후, 해결책은 http://를 href에 추가하는 것입니다.
<a href="http://www.URL.com">Go somewhere</a>
사용한window.location.href='http://external-url';
저에게 리디렉션은 Chrome에서는 작동했지만 Firefox에서는 작동하지 않았습니다.다음 코드로 문제가 해결되었습니다.
window.location.assign('http://external-url');
글로벌 윈도우 객체를 직접 조작하고 싶지 않아서 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 = 'redirect_url';
다른 방법 각도 문서:
각도에서 문서를 가져오면 아래와 같이 문서를 주입해야 합니다. 그렇지 않으면 오류가 발생합니다.
import { DOCUMENT } from '@angular/common';
export class AppComponent {
constructor(
@Inject(DOCUMENT) private document: Document
) {}
this.document.location.href = 'redirect_url';
}
위의 솔루션 중 어떤 것도 저에게 효과가 없었습니다. 저는 그냥 덧붙였습니다.
window.location.href = "www.google.com"
event.preventDefault();
이것은 저에게 효과가 있었습니다.
또는 사용해 보십시오.
window.location.replace("www.google.com");
@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>
구성 요소의 .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='http://www.google.com/';
언급URL : https://stackoverflow.com/questions/34338440/how-to-redirect-to-an-external-url-in-angular2
'programing' 카테고리의 다른 글
| 이클립스 인텔리센스? (0) | 2023.04.26 |
|---|---|
| 웹 API 라우팅 - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id} (0) | 2023.04.26 |
| [NSBundlebundleForClass:[self class]]에 해당하는 신속한 기능 (0) | 2023.04.26 |
| 다트에서 두 개의 목록을 결합하려면 어떻게 해야 합니까? (0) | 2023.04.26 |
| 엑셀 파일 작업을 위한 간단하고 신뢰할 수 있는 C 라이브러리는 무엇입니까? (0) | 2023.04.26 |