在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页。
路由器有这个历史信息吗?
当前回答
试试routerLink = " - LASTPAGE”
其他回答
我做了一个按钮,我可以在我的应用程序的任何地方重复使用。
创建这个组件
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材质,如果你不使用这个库,那么移除垫子按钮和颜色。
实际上,你可以利用内置的位置服务,它拥有一个“返回”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};线条很重要。
只需使用Location,这是一个Angular服务,应用程序可以使用它与浏览器的URL进行交互。
导入:
import { Location } from '@angular/common';
注射:
constructor(private location: Location) { }
简单地使用它:
goBack() {
this.location.back(); // Navigates back in the platform's history
}
2022 利用你的应用程序路由-更多的是一种“角度方法”,而不是访问浏览器的位置对象来获取导航历史。 想想你为什么需要用户返回,以及“返回”在应用程序及其路由的更广泛的上下文中意味着什么。
例如,从子路由返回到父路由
this.router.navigate(['..'], {relativeTo: this.route});
您还可以阅读以前的导航
previousNavigation:先前成功的导航对象。只有 一个先前的导航是可用的,因此这个先前的 Navigation对象的previousNavigation为空值。
<按钮返回按钮>返回</button>
你可以把它放到一个指令中,这个指令可以附加到任何可点击的元素上:
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();
}
}
用法:
<button backButton>BACK</button>