如何在Angular2应用程序中返回上一页?

9
我正在构建一个由路由器提供多个视图的单页应用程序。
我阅读的大部分信息都说要将location:Location注入为服务,然后使用(click)='location.back'返回上一个视图。
但这对我不起作用,因为如果你从特定视图开始并点击返回,你会退出应用程序并返回到先前的网站。当使用这种导航方法时,我也经常遇到页面重新加载的情况。在ng2应用程序中是否有历史API或其他处理导航的方法?

听起来像是正常的行为。当没有页面可以返回时,您希望浏览器去哪里?您可以将UI中的“后退”链接替换为一个链接,该链接可以将用户带到可以充当“父屏幕”的屏幕上。例如,如果用户正在查看特定项目,则链接可以将其带到项目列表;如果他们深入菜单分支,则链接可以将其带到父菜单项等。 - AngularChef
1
我可以这样做,但有没有办法检测后向链接是否会转到不同的主机或主机名?我并不总是希望导航返回仪表板,有时他们会从另一个页面跳转。 - userqwert
我明白。CanDeactivate 允许您在离开路由之前运行一些代码,但恐怕它仅适用于从一个 Angular 路由导航到另一个路由,而不是从路由导航到外部 URL。 - AngularChef
1
我会用纯JS来实现。你可以使用window.onpopstatewindow.onunload监听URL的变化,并做出相应的反应。 - AngularChef
@AngularFrance 我想你可能是对的,我会写一个不用 Angular 的服务来完成它。 - userqwert
4个回答

21

你可以使用 Angular Common 中的位置信息,例如:

import {Location} from '@angular/common';
    constructor(private _location: Location){ }
    goback(){
        this._location.back();
    }

1
是的,这就是我正在做的事情,也是我在问题中写的... 我正在寻找一种不会意外退出应用程序的方法。你也不需要在这里绑定一个goBack方法,你可以直接在模板中访问位置服务。 - userqwert
是的,在 HTML 中使用如下代码:<a (click) = "_location.back()">返回</a>但请确保 public _location:Location - Amee Prajapati

1
使用这个:
window.history.back();

我不知道为什么会被踩。从技术上讲,这是可行的......即使这不是首选方法。 - krummens
这正是@angular/common中Location服务的back()方法在通常情况下(使用@angular/platform-browser模块时)在幕后执行的操作。Angular方法的优点在于它更通用,并且也适用于Angular支持的其他平台。 - Cito

0

可能会有帮助

history: string[] = [];

constructor(private router: Router) {
    router.events
        .filter(event => event instanceof NavigationEnd)
        .subscribe(event => {
            this.history.push(event.url);
        });
}

onBack() {
    if (this.history.length > 1) {
        // pop current page
        this.history.pop();
        // pop previous page (later it will be added)
        this.history.pop();
        window.history.back();
    }
}

onHome() {
    window.location.replace(window.location.origin);
}

0

在 Ionic 4 中,这对我起作用:

import { Location } from '@angular/common';

...
constructor(private location: Location) {}

back() {
  this.location.back();
}
...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接