Cambiar parámetros de ruta sin recargar en angular 2


Estoy haciendo un sitio web de bienes raíces utilizando angular 2, google maps, etc. y cuando un usuario cambia el centro del mapa realizo una búsqueda en la api indicando la posición actual del mapa así como el radio. La cosa es que quiero reflejar esos valores en la url sin recargar toda la página. Es eso posible? He encontrado algunas soluciones usando AngularJS 1.x pero nada sobre angular 2.

Author: Splaktar, 2016-02-25

6 answers

Puedes usar location.go(url) que básicamente cambiará tu url, sin cambios en la ruta de aplicación.

NOTA esto podría causar otro efecto como redirigir a la ruta secundaria desde la ruta actual.

Pregunta relacionada lo que describe location.go no intimará a Router para que ocurran cambios.

 42
Author: Pankaj Parkar,
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:26:32

A partir de RC6, puede hacer lo siguiente para cambiar la URL sin cambiar el estado y, por lo tanto, mantener su historial de rutas

import {OnInit} from '@angular/core';
import {Location} from '@angular/common';

@Component({
  selector: 'example-component',
  templateUrl: 'xxx.html'
})
export class ExampleComponent implements OnInit
{
  constructor( private location: Location )
  {}

  ngOnInit()
  {    
    this.location.replaceState("/some/newstate/");
  }
}
 46
Author: user590696,
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-12 09:24:24

Usar location.go(url) es el camino a seguir, pero en lugar de codificar la url , considere generarla usando router.createUrlTree().

Dado que desea hacer la siguiente llamada al router: this.router.navigate([{param: 1}], {relativeTo: this.activatedRoute}) pero sin recargar el componente, se puede reescribir como:

const url = this
        .router
        .createUrlTree([{param: 1}], {relativeTo: this.activatedRoute})
        .toString();

 this.location.go(url);
 26
Author: golfadas,
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-09-12 09:52:05

Tuve grandes problemas para hacer que esto funcionara en las versiones de RCX de angular2. El paquete de ubicación se ha movido, y la ubicación en ejecución.go () dentro de constructor () no funcionará. Necesita ser ngOnInit () o más tarde en el ciclo de vida. He aquí un ejemplo de código:

import {OnInit} from '@angular/core';
import {Location} from '@angular/common';

@Component({
  selector: 'example-component',
  templateUrl: 'xxx.html'
})
export class ExampleComponent implements OnInit
{
  constructor( private location: Location )
  {}

  ngOnInit()
  {    
    this.location.go( '/example;example_param=917' );
  }
}

Aquí están los recursos angulares sobre la materia: https://angular.io/docs/ts/latest/api/common/index/Location-class.html https://angular.io/docs/ts/latest/api/common/index/LocationStrategy-class.html

 6
Author: Luke Dupin,
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-06-10 05:41:56

Para cualquier persona como yo que encuentre esta pregunta, lo siguiente podría ser útil.

Tuve un problema similar e inicialmente intenté usar la ubicación.ve y ubicación.replaceState as suggested in other answers here. Sin embargo, me encontré con problemas cuando tuve que navegar a otra página de la aplicación porque la navegación era relativa a la ruta actual y la ruta actual no se estaba actualizando por ubicación.ir o ubicación.replaceState (el router no sabe nada acerca de lo que estos hacen a la URL)

En esencia, necesitaba una solución que NO recargara la página/componente cuando cambiara el parámetro de ruta, sino que actualizara el estado de la ruta internamente.

Terminé usando parámetros de consulta. Puedes encontrar más información aquí: https://angular-2-training-book.rangle.io/handout/routing/query_params.html

Así que si necesita hacer algo como guardar un pedido y obtener un ID de pedido, puede actualizar la URL de su página como se muestra a continuación. Actualización de la ubicación de un centro y los datos en un mapa serían similares

// let's say we're saving an order. Initally the URL is just blah/orders
save(orderId) {
    // [Here we would call back-end to save the order in the database]

    this.router.navigate(['orders'], { queryParams: { id: orderId } });
    // now the URL is blah/orders?id:1234. We don't reload the orders
    // page or component so get desired behaviour of not seeing any 
    // flickers or resetting the page.
}

Y se lleva un registro de ello dentro del método ngOnInit como:

ngOnInit() {
    this.orderId = this.route
        .queryParamMap
        .map(params => params.get('id') || null);
    // orderID is up-to-date with what is saved in database now, or if
    // nothing is saved and hence no id query paramter the orderId variable
    // is simply null.
    // [You can load the order here from its ID if this suits your design]
}

Si necesita ir directamente a la página de pedidos con un pedido nuevo (no guardado), puede hacer:

this.router.navigate(['orders']);

O si necesita ir directamente a la página de pedidos para un pedido existente (guardado), puede hacer:

this.router.navigate(['orders'], { queryParams: { id: '1234' } });
 5
Author: TornadoAli,
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-09-12 13:59:46

Para mí fue en realidad una mezcla de ambos con Angular 4.4.5.

Usando el router.navigate siguió destruyendo mi url al no respetar la parte realtiveTo: ActivatedRoute.

He terminado con:

this._location.go(this._router.createUrlTree([this._router.url], { queryParams: { profile: value.id } }).toString())
 2
Author: Patrick P.,
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-20 13:32:00