在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页。
路由器有这个历史信息吗?
当前回答
在Angular 2的最终版本中。X / 4。x -这里是文档https://angular.io/api/common/Location
/* typescript */
import { Location } from '@angular/common';
// import stuff here
@Component({
// declare component here
})
export class MyComponent {
// inject location into component constructor
constructor(private location: Location) { }
cancel() {
this.location.back(); // <-- go back to previous location on cancel
}
}
其他回答
RC4:
import {Location} from '@angular/common';
从beta 18开始:
import {Location} from 'angular /platform/common';
如果你使用的是最新的Angular/TypeScript,请确保你显式导入
import { Location } from '@angular/common';
and
onCancel() {
this.location.back();
}
实际上,你可以利用内置的位置服务,它拥有一个“返回”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.back()(例如,通过按下工具栏中的<- back按钮),你会回到浏览器的主页面,而不是去应用程序中的其他地方。
这是我检查这个的方法:
import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';
@Component({
selector: 'app-foo',
template: ''
})
export class FooComponent {
private readonly canGoBack: boolean;
constructor(
private readonly route: ActivatedRoute,
private readonly router: Router,
private readonly location: Location
) {
// This is where the check is done. Make sure to do this
// here in the constructor, otherwise `getCurrentNavigation()`
// will return null.
this.canGoBack = !!(this.router.getCurrentNavigation()?.previousNavigation);
}
goBack(): void {
if (this.canGoBack) {
// We can safely go back to the previous location as
// we know it's within our app.
this.location.back();
} else {
// There's no previous navigation.
// Here we decide where to go. For example, let's say the
// upper level is the index page, so we go up one level.
this.router.navigate(['..'], {relativeTo: this.route});
}
}
}
我们检查加载当前路由的导航是否有前一个兄弟。这必须在导航过程仍处于活动状态时在构造函数中完成。
但也有一些注意事项:
即使之前的位置实际上在我们的应用程序中,但页面被刷新,canGoBack也将为false。 用户可能想通过点击浏览器的返回按钮“返回”到上一页(goBack()发生的地方),但由于应用程序返回历史而不是按一个新的位置,用户将会返回得更远,可能会感到困惑。