在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页。
路由器有这个历史信息吗?
当前回答
要返回而不刷新页面,我们可以像下面这样在html中做 javascript: history.back ()
<a class="btn btn-danger" href="javascript:history.back()">Go Back</a>
其他回答
实际上,你可以利用内置的位置服务,它拥有一个“返回”API。
这里(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();
}
}
编辑:正如@charith所提到的。Location应该从@angular/common中导入,所以从@angular/common中导入{Location};线条很重要。
这是我想出来的,你也可以查一下是否有上一页。 确保在你的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);
}
}
要返回而不刷新页面,我们可以像下面这样在html中做 javascript: history.back ()
<a class="btn btn-danger" href="javascript:history.back()">Go Back</a>
是的,你能做到。在你的typescript组件上编写这段代码,然后享受吧!
import { Location } from '@angular/common'
import { Component, Input } from '@angular/core'
@Component({
selector: 'return_page',
template: `<button mat-button (click)="onReturn()">Back</button>`,
})
export class ReturnPageComponent {
constructor(private location: Location) { }
onReturn() {
this.location.back();
}
}
试试routerLink = " - LASTPAGE”