Cómo recargar la ruta actual con el router angular 2
Estoy usando angular 2 con la estrategia de hashlocation.
El componente se carga con esa ruta:
"departments/:id/employees"
Hasta ahora bien.
Después de hacer un guardado por lotes exitoso de varias filas de tabla editadas, quiero recargar la url de ruta actual a través de:
this.router.navigate([`departments/${this.id}/employees`]);
Pero no pasa nada, ¿por qué?
18 answers
Si su navigate() no cambia la URL que ya se muestra en la barra de direcciones de su navegador, el enrutador no tiene nada que ver. No es tarea del router actualizar los datos. Si desea actualizar los datos, cree un servicio inyectado en el componente e invoque la función load en el servicio. Si se recuperan los nuevos datos, se actualizará la vista a través de enlaces.
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-12-05 21:01:08
Encontré esta solución en una solicitud de características de GitHub para Angular:
this._router.routeReuseStrategy.shouldReuseRoute = function(){
return false;
};
this._router.events.subscribe((evt) => {
if (evt instanceof NavigationEnd) {
this._router.navigated = false;
window.scrollTo(0, 0);
}
});
He intentado añadir esto a mi aplicación.componente.ts ngOnInit
función, y seguro funcionó. Todos los clics posteriores en el mismo enlace ahora recargan component
y los datos.
Enlace a la solicitud de característica original de GitHub
El crédito va a mihaicux2 en GitHub.
Probé esto en la versión 4.0.0-rc.3
con import { Router, NavigationEnd } from '@angular/router';
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-08-17 14:01:54
Esto se puede hacer ahora en Angular 5.1 usando la propiedad onSameUrlNavigation
de la configuración del router.
He añadido un blog explicando cómo aquí, pero la esencia de la misma es la siguiente
En la configuración del enrutador habilite la opción onSameUrlNavigation
, ajustándola a 'reload'
. Esto hace que el enrutador active un ciclo de eventos cuando intenta navegar a una ruta que está activa ya.
@ngModule({
imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})],
exports: [RouterModule],
})
En sus definiciones de ruta, establezca runGuardsAndResolvers
en always
. Esto le dirá al enrutador que siempre arranque los ciclos de guardias y resolutores, disparando eventos asociados.
export const routes: Routes = [
{
path: 'invites',
component: InviteComponent,
children: [
{
path: '',
loadChildren: './pages/invites/invites.module#InvitesModule',
},
],
canActivate: [AuthenticationGuard],
runGuardsAndResolvers: 'always',
}
]
Finalmente, en cada componente que desee habilitar la recarga, debe manejar los eventos. Esto se puede hacer importando el enrutador, vinculando los eventos e invocando un método de inicialización que restablece el estado de su componente y vuelve a obtener los datos si es necesario.
export class InviteComponent implements OnInit, OnDestroy {
navigationSubscription;
constructor(
// … your declarations here
private router: Router,
) {
// subscribe to the router events. Store the subscription so we can
// unsubscribe later.
this.navigationSubscription = this.router.events.subscribe((e: any) => {
// If it is a NavigationEnd event re-initalise the component
if (e instanceof NavigationEnd) {
this.initialiseInvites();
}
});
}
initialiseInvites() {
// Set default values and re-fetch any data you need.
}
ngOnDestroy() {
if (this.navigationSubscription) {
this.navigationSubscription.unsubscribe();
}
}
}
Con todos de estos pasos en su lugar, debe tener la recarga de rutas habilitada.
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-15 17:54:54
Poco complicado: utilice la misma ruta con algunos parámetros ficticios. Por ejemplo-
refresh(){
this.router.navigate(["/same/route/path?refresh=1"]);
}
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-03-12 22:27:14
Crear una función en el controlador que redirige a la ruta esperada como así
redirectTo(uri:string){
this.router.navigateByUrl('/DummyComponent', {skipLocationChange: true}).then(()=>
this.router.navigate([uri]));}
Entonces úsalo así
this.redirectTo('//place your uri here');
Esta función redirigirá a una ruta ficticia y volverá rápidamente a la ruta de destino sin que el usuario se dé cuenta.
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-08-29 07:34:44
Angular 2-4 ruta de recarga hack
Para mí, usar este método dentro de un componente raíz (componente, que está presente en cualquier ruta) funciona:
onRefresh() {
this.router.routeReuseStrategy.shouldReuseRoute = function(){return false;};
let currentUrl = this.router.url + '?';
this.router.navigateByUrl(currentUrl)
.then(() => {
this.router.navigated = false;
this.router.navigate([this.router.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
2018-01-22 11:08:39
Para mí trabaja hardcoding con
this.router.routeReuseStrategy.shouldReuseRoute = function() {
return false;
// or
return true;
};
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-01-07 09:58:32
Encontró una solución rápida y directa que no requiere jugar con el funcionamiento interno de angular:
Básicamente: Simplemente cree una ruta alternativa con el mismo módulo de destino y simplemente alterne entre ellos:
const routes: Routes = [
{
path: 'gesuch',
loadChildren: './sections/gesuch/gesuch.module#GesuchModule'
},
{
path: 'gesuch-neu',
loadChildren: './sections/gesuch/gesuch.module#GesuchModule'
}
];
Y aquí el menú toggeling:
<ul class="navigation">
<li routerLink="/gesuch-neu" *ngIf="'gesuch' === getSection()">Gesuch</li>
<li routerLink="/gesuch" *ngIf="'gesuch' !== getSection()">Gesuch</li>
</ul>
Espero que ayude:)
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-23 12:50:49
En mi caso:
const navigationExtras: NavigationExtras = {
queryParams: { 'param': val }
};
this.router.navigate([], navigationExtras);
Funciona correctamente
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-12-26 14:07:56
Implementa OnInit y llama a ngOnInit() en el método para route.navigate ()
Ver un ejemplo:
export class Component implements OnInit {
constructor() { }
refresh() {
this.router.navigate(['same-route-here']);
this.ngOnInit(); }
ngOnInit () {
}
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-03-14 22:22:14
Resolvió un escenario similar usando un componente ficticio y una ruta para reload
, que en realidad hace un redirect
. Esto definitivamente no cubre todos los escenarios de usuario, pero solo funcionó para mi escenario.
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Http } from '@angular/http';
@Component({
selector: 'reload',
template: `
<h1>Reloading...</h1>
`,
})
export class ReloadComponent implements OnInit{
constructor(private router: Router, private route: ActivatedRoute) {
}
ngOnInit() {
const url = this.route.snapshot.pathFromRoot.pop().url.map(u => u.path).join('/');
this.router.navigateByUrl(url);
}
}
El enrutamiento está cableado para capturar todas las url usando un comodín:
import { RouterModule } from '@angular/router';
import { NgModule } from '@angular/core';
import { LoginViewComponent } from './views/login/login.component';
import { HomeViewComponent } from './views/home/home.component';
import { ReloadComponent } from './views/reload/reload.component';
@NgModule({
declarations: [
LoginViewComponent, HomeViewComponent, ReloadComponent
],
imports: [
RouterModule.forRoot([
{ path: 'login', component: LoginViewComponent },
{ path: 'home', component: HomeViewComponent },
{
path: 'reload',
children: [{
path: '**',
component: ReloadComponent
}]
},
{ path: '**', redirectTo: 'login'}
])
],
exports: [
RouterModule,
],
providers: [],
})
export class AppRoutingModule {}
Para usar esto, solo tenemos que añadir reload a la url a la que queremos ir:
this.router.navigateByUrl('reload/some/route/again/fresh', {skipLocationChange: true})
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-28 09:06:22
En la página de recarga de cambio de param no sucederá. Esta es una muy buena característica. No hay necesidad de recargar la página, pero debemos cambiar el valor del componente. El método paramChange llamará al cambio de url. Así que podemos actualizar los datos del componente
/product/: id / details
import { ActivatedRoute, Params, Router } from ‘@angular/router’;
export class ProductDetailsComponent implements OnInit {
constructor(private route: ActivatedRoute, private router: Router) {
this.route.params.subscribe(params => {
this.paramsChange(params.id);
});
}
// Call this method on page change
ngOnInit() {
}
// Call this method on change of the param
paramsChange(id) {
}
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-08-11 07:20:48
Suscribirse a los cambios de parámetros de ruta
// parent param listener ie: "/:id"
this.route.params.subscribe(params => {
// do something on parent param change
let parent_id = params['id']; // set slug
});
// child param listener ie: "/:id/:id"
this.route.firstChild.params.subscribe(params => {
// do something on child param change
let child_id = params['id'];
});
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-26 16:55:13
Supongamos que la ruta del componente que desea actualizar es view
, luego use esto:
this.router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot) {
if (future.url.toString() === 'view' && curr.url.toString() === future.url.toString()) {
return false;
}
return (future.routeConfig === curr.routeConfig);
};
Puede agregar un debugger
dentro del método para saber cuál es la ruta exacta que vendrá después de navegar a "departments/:id/employees"
.
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-21 14:08:18
Esto funcionó para mí:
let url = `departments/${this.id}/employees`;
this.router.navigated = false;
this.router.navigateByUrl(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-08-30 08:18:53
Recargar ruta actual en angular 2 enlace muy útil para recargar ruta actual en angualr 2 o 4
En este definir dos técnicas para hacer esto
- con parámetros de consulta ficticios
- con ruta ficticia
Para más información ver el enlace anterior
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-02-08 06:26:18
Prueba esto
Ventana.open('dashboard', '_self');
Su método antiguo pero funciona en todas las versiones de angular, donde redirige en ruta y actualiza la página.
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-03-05 08:47:08
Simplemente use el método de recarga javascript nativo:
reloadPage() {
window.location.reload();
}
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-02-20 16:55:10