在Angular 2中,有没有一种聪明的方法返回上一页?
类似于
this._router.navigate(LASTPAGE);
例如,页面C有一个返回按钮,
从页面A跳转到页面C,点击按钮,返回页面A。
从页面B跳转到页面C,点击按钮,返回页面B。
在Angular 2中,有没有一种聪明的方法返回上一页?
类似于
this._router.navigate(LASTPAGE);
例如,页面C有一个返回按钮,
从页面A跳转到页面C,点击按钮,返回页面A。
从页面B跳转到页面C,点击按钮,返回页面B。
this.router.navigate(["user/edit"], { queryParams: { returnUrl: this.router.url }
在您的组件中读取此查询参数
this.router.queryParams.subscribe((params) => {
this.returnUrl = params.returnUrl;
});
如果returnUrl存在,则启用“后退”按钮,当用户点击“后退”按钮时。this.router.navigateByUrl(this.returnUrl); // Hint taken from Sasxa
这应该能够导航到上一页。我认为使用上述方法比使用location.back更安全,考虑到用户直接着陆在您的页面上并且如果他使用location.back按下返回按钮,它将重定向用户到以前的页面,这将不是您的网页。
import {Location} from '@angular/common';
另一种解决方案:
window.history.back();
import { Location } from '@angular/common';
和
onCancel() {
this.location.back();
}
import {Location} from 'angular2/platform/common';
2022
利用您的应用程序路由 - 更像是“Angular方法”,而不是访问浏览器的位置对象来查看导航历史记录。考虑为什么需要用户返回,并且在应用程序及其路由的更广泛上下文中,“返回”意味着什么。
例如,从子路由返回到父路由。
this.router.navigate(['..'], {relativeTo: this.route});
您还可以阅读有关上一个导航的内容。
previousNavigation:先前成功的导航对象。只有一个上一个导航可用,因此此先前的导航对象对其自身的previousNavigation具有空值。
<a class="btn btn-danger" href="javascript:history.back()">Go Back</a>
我想到了这个,你也可以检查是否有上一页。 确保在你的appComponent中使用该服务。
import { Injectable } from '@angular/core';
import { Location } from '@angular/common';
import { NavigationEnd, Router } from '@angular/router';
interface HistoryData {
previousPage: string | null,
currentPage: string | null,
}
@Injectable({ providedIn: 'root' })
export class GoBackService {
private historyData: HistoryData = { previousPage: null, currentPage: null };
constructor(private router: Router, private location: Location) {
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
this.historyData.previousPage = this.historyData.currentPage;
this.historyData.currentPage = event.urlAfterRedirects;
}
});
}
public goBack(): void {
if (this.historyData.previousPage) this.location.back();
}
public canGoBack(): boolean {
return Boolean(this.historyData.previousPage);
}
}
导入:
import { Location } from '@angular/common';
import { Router } from '@angular/router';
构造函数:
constructor(private readonly router: Router, private readonly location: Location) {
location.onUrlChange(() => this.canGoBack = !!this.router.getCurrentNavigation()?.previousNavigation);
}
可选项,避免在应用程序外部返回:
private canGoBack: boolean = false;
constructor(private router:Router,private location:Location){
this.canGoBack = !!(this.router.getCurrentNavigation()?.previousNavigation);
}
返回:
goBack(): void {
if (this.canGoBack) {
this.location.back();
}
}
HTML:
<button (click)="goBack()"></button>
我正在使用这种方式:
import { Location } from '@angular/common'
import { Component, Input } from '@angular/core'
@Component({
selector: 'Back_page',
template: `<button (click)="onBack()">Back</button>`,
})
export class BackPageComponent {
constructor(private location: Location) { }
onBack() {
this.location.back();// <-- go back to previous location
}
}