Cómo redirigir a una URL externa en Angular2?
Cuál es el método para redirigir al usuario a una URL completamente externa en Angular 2. Por ejemplo, si necesito redirigir al usuario a un servidor OAuth2 para autenticarme, ¿cómo lo haría?
Location.go()
, Router.navigate()
, y Router.navigateByUrl()
están bien para enviar al usuario a otra sección (ruta) dentro de la aplicación Angular 2, pero no puedo ver cómo podrían usarse para redirigir a un sitio externo?
9 answers
Puede usar esto-> window.location.href = '...';
Esto cambiaría la página a lo que quieras..
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-13 18:02:37
Un enfoque angular de los métodos descritos anteriormente es importar DOCUMENT
desde @angular/common
(o @angular/platform-browser
en Angular
document.location.href = 'https://stackoverflow.com';
Dentro de una función.
Vaya página.componente.ts
import { DOCUMENT } from '@angular/common';
...
constructor(@Inject(DOCUMENT) private document: any) { }
goToUrl(): void {
this.document.location.href = 'https://stackoverflow.com';
}
Vaya página.componente.html
<button type="button" (click)="goToUrl()">Click me!</button>
Echa un vistazo al repositorio plateformBrowser para obtener más información.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-11 16:27:31
La solución, como dijo Dennis Smolek, es muy simple. Establezca window.location.href
en la URL a la que desea cambiar y simplemente funciona.
Por ejemplo, si tuviera este método en el archivo de clase de su componente (controlador):
goCNN() {
window.location.href='http://www.cnn.com/';
}
Entonces podrías llamarlo simplemente con la llamada apropiada (click)
en un botón (o lo que sea) en tu plantilla:
<button (click)="goCNN()">Go to CNN</button>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:45
Si necesitas à target = "_blank" , puedes usar window.abierto :
gotoGoogle() : void {
window.open("https://www.google.com", "_blank");
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-07 11:57:42
Si ha estado utilizando el gancho de ciclo de vida OnDestry, podría estar interesado en usar algo como esto antes de llamar a window.ubicación.href=...
this.router.ngOnDestroy();
window.location.href = 'http://www.cnn.com/';
Que activará la devolución de llamada OnDestry en su componente que podría gustarle.
Ohh, y también:
import { Router } from '@angular/router';
Es donde se encuentra el router.
- - - EDITAR--- Lamentablemente, podría haber estado equivocado en el ejemplo anterior. Al menos no está funcionando como exepected en mi código de producción en este momento-así que, hasta que tenga tiempo para investigue más, lo resuelvo de esta manera (ya que mi aplicación realmente necesita el gancho cuando sea posible)
this.router.navigate(["/"]).then(result=>{window.location.href = 'http://www.cnn.com/';});
Básicamente enrutamiento a cualquier ruta (ficticia) para forzar el gancho, y luego navegar como se solicita.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-22 09:33:11
Lo hice usando la ubicación Angular 2 ya que no quería manipular el objeto ventana global yo mismo.
Https://angular.io/docs/ts/latest/api/common/index/Location-class.html#!#prepareExternalUrl-anchor
Se puede hacer así:
import {Component} from '@angular/core';
import {Location} from '@angular/common';
@Component({selector: 'app-component'})
class AppCmp {
constructor(location: Location) {
location.go('/foo');
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-02 09:58:48
Usé ventana.ubicación.href = ' http://external-url';
Para mí las redirecciones funcionaron en Chrome, pero no funcionó en Firefox. El siguiente código resolvió mi problema:
window.location.assign('http://external-url');
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-28 08:34:27
Después de arrancarme la cabeza, la solución es solo agregar http:// a href.
<a href="http://www.URL.com">Go somewhere</a>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-12 17:38:10
En tu componente .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';
}
}
En tu componente .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;**
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-10 13:47:24