Cómo volver a la última página
¿Hay una manera inteligente de regresar a la última página en Angular 2?
Algo como
this._router.navigate(LASTPAGE);
Por ejemplo, la página C tiene un botón Volver,
-
Página A - > Página C, haga clic en ella, volver a la página A.
-
Página B - > Página C, haga clic en ella, volver a la página B.
¿El router tiene esta información del historial?
12 answers
En realidad, puede aprovechar el servicio de ubicación integrado, que posee una api "Back".
Aquí (typescript):
import {Component} from '@angular/core';
import {Location} from '@angular/common';
@Component({
// component's declarations here
})
class SomeComponent {
constructor(private _location: Location) {
}
backClicked() {
this._location.back();
}
}
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-11-07 19:54:53
En la versión final de Angular 2.x / 4.x-aquí están los documentos https://angular.io/docs/ts/latest/api/common/index/Location-class.html
/* typescript */
import { Location } from '@angular/common';
// import stuff here
@Component({
// declare component here
})
export class MyComponent {
// inject location into component constructor
constructor(private location: Location) { }
cancel() {
this.location.back(); // <-- go back to previous location on cancel
}
}
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-11-22 08:59:15
Puede implementar routerOnActivate()
método en su clase de ruta, proporcionará información sobre la ruta anterior.
routerOnActivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction) : any
Luego puede usar router.navigateByUrl()
y pasar los datos generados desde ComponentInstruction
. Por ejemplo:
this._router.navigateByUrl(prevInstruction.urlPath);
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-02-17 03:58:49
Probado con Angular 5.2.9
Si usa un ancla en lugar de un botón, debe convertirlo en un enlace pasivo con href="javascript:void(0)"
para que la Ubicación Angular funcione.
app.component.ts
import { Component } from '@angular/core';
import { Location } from '@angular/common';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
constructor( private location: Location ) {
}
goBack() {
// window.history.back();
this.location.back();
console.log( 'goBack()...' );
}
}
app.component.html
<!-- anchor must be a passive link -->
<a href="javascript:void(0)" (click)="goBack()">
<-Back
</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-04-01 09:46:02
También funciona para mí cuando necesito retroceder como en el sistema de archivos. P.d. @angular: "^5.0.0"
<button type="button" class="btn btn-primary" routerLink="../">Back</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
2018-01-04 16:28:53
En RC4:
import {Location} from '@angular/common';
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-18 13:08:46
Hice un botón que puedo reutilizar en cualquier lugar de mi aplicación.
Crear este componente
import { Location } from '@angular/common';
import { Component, Input } from '@angular/core';
@Component({
selector: 'back-button',
template: `<button mat-button (click)="goBack()" [color]="color">Back</button>`,
})
export class BackButtonComponent {
@Input()color: string;
constructor(private location: Location) { }
goBack() {
this.location.back();
}
}
Luego agréguelo a cualquier plantilla cuando necesite un botón atrás.
<back-button color="primary"></back-button>
Nota: Esto está utilizando Material Angular, si no está utilizando esa biblioteca, elimine mat-button
y color
.
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-30 01:16:00
La forma en que lo hice mientras navegaba a una página diferente agrega un parámetro de consulta pasando la ubicación actual
this.router.navigate(["user/edit"], { queryParams: { returnUrl: this.router.url }
Lea este parámetro de consulta en su componente
this.router.queryParams.subscribe((params) => {
this.returnUrl = params.returnUrl;
});
Si returnUrl está presente, habilite el botón atrás y cuando el usuario haga clic en el botón atrás
this.router.navigateByUrl(this.returnUrl); // Hint taken from Sasxa
Esto debería ser capaz de navegar a la página anterior. En lugar de usar la ubicación.creo que el método anterior es más seguro considere el caso en el que el usuario aterriza directamente en su página y si presiona el botón atrás con ubicación.volver se redirige al usuario a la página anterior que no será su página web.
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-14 05:10:31
En angular 4 use preserveQueryParams
, por ejemplo:
url: /list?page=1
<a [routerLink]="['edit',id]" [preserveQueryParams]="true"></a>
Al hacer clic en el enlace, se le redirige edit/10?page=1
, preservando los parámetros
Ref: https://angular.io/docs/ts/latest/guide/router.html#! # link-parameters-array
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-18 13:12:02
Otra solución
window.history.back();
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-17 16:15:02
Desde beta 18:
import {Location} from 'angular2/platform/common';
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-06-02 13:59:11
Puede poner esto en una directiva, que se puede adjuntar a cualquier elemento clickable:
import { Directive, HostListener } from '@angular/core';
import { Location } from '@angular/common';
@Directive({
selector: '[backButton]'
})
export class BackButtonDirective {
constructor(private location: Location) { }
@HostListener('click')
onClick() {
this.location.back();
}
}
Uso:
<button backButton>BACK</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
2018-10-10 08:07:02