在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页。
路由器有这个历史信息吗?
当前回答
我做了一个按钮,我可以在我的应用程序的任何地方重复使用。
创建这个组件
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();
}
}
然后在需要后退按钮时将其添加到任何模板中。
<back-button color="primary"></back-button>
注意:这里使用的是Angular材质,如果你不使用这个库,那么移除垫子按钮和颜色。
其他回答
要返回而不刷新页面,我们可以像下面这样在html中做 javascript: history.back ()
<a class="btn btn-danger" href="javascript:history.back()">Go Back</a>
也为我工作时,我需要移动回文件系统。 P.S. @angular: "^5.0.0"
<button type="button" class="btn btn-primary" routerLink="../">Back</button>
在这些精彩的答案之后,我希望我的答案能找到一些人,并帮助他们。我编写了一个小服务来跟踪路线历史。开始了。
import { Injectable } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs/operators';
@Injectable()
export class RouteInterceptorService {
private _previousUrl: string;
private _currentUrl: string;
private _routeHistory: string[];
constructor(router: Router) {
this._routeHistory = [];
router.events
.pipe(filter(event => event instanceof NavigationEnd))
.subscribe((event: NavigationEnd) => {
this._setURLs(event);
});
}
private _setURLs(event: NavigationEnd): void {
const tempUrl = this._currentUrl;
this._previousUrl = tempUrl;
this._currentUrl = event.urlAfterRedirects;
this._routeHistory.push(event.urlAfterRedirects);
}
get previousUrl(): string {
return this._previousUrl;
}
get currentUrl(): string {
return this._currentUrl;
}
get routeHistory(): string[] {
return this._routeHistory;
}
}
你可以在你的路由类上实现routerOnActivate()方法,它会提供之前路由的信息。
routerOnActivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction) : any
然后你可以使用router.navigateByUrl()并传递ComponentInstruction生成的数据。例如:
this._router.navigateByUrl(prevInstruction.urlPath);
试试routerLink = " - LASTPAGE”