在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页。
路由器有这个历史信息吗?
当前回答
RC4:
import {Location} from '@angular/common';
其他回答
从beta 18开始:
import {Location} from 'angular /platform/common';
进口:
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>
检测到的未更改组件的@Parziphal答案版本:
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);
}
goBack(): void {
if (this.canGoBack) {
this.location.back();
}
}
我这样做的方式,而导航到不同的页面添加一个查询参数通过传递当前位置
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
这应该能够导航到前一页。而不是使用位置。我觉得上面的方法是更安全的考虑情况下,用户直接登陆到你的页面,如果他按后退按钮的位置。回到它将重定向用户到前一页,这将不是你的网页。
实际上,你可以利用内置的位置服务,它拥有一个“返回”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};线条很重要。