Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在angular2应用程序中导航回来?_Javascript_Angular - Fatal编程技术网

Javascript 如何在angular2应用程序中导航回来?

Javascript 如何在angular2应用程序中导航回来?,javascript,angular,Javascript,Angular,我正在构建一个单页应用程序,由路由器提供多个视图 我读过的大部分信息都说要将location:location作为服务注入,然后使用(单击)=“location.back”返回视图 这对我来说不起作用,就好像你从某个视图开始,然后单击“上一步”,最后退出应用程序并转到上一个网站。当我使用它作为导航方法时,我也会频繁地重新加载页面。在ng2应用程序中是否有历史API或其他方式来处理导航?使用以下方法: window.history.back(); 您可以使用“角度公用”中的“位置” 比如: 可能

我正在构建一个单页应用程序,由路由器提供多个视图

我读过的大部分信息都说要将
location:location
作为服务注入,然后使用
(单击)=“location.back”
返回视图

这对我来说不起作用,就好像你从某个视图开始,然后单击“上一步”,最后退出应用程序并转到上一个网站。当我使用它作为导航方法时,我也会频繁地重新加载页面。在ng2应用程序中是否有历史API或其他方式来处理导航?

使用以下方法:

window.history.back();

您可以使用“角度公用”中的“位置” 比如:

可能会有帮助

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);
}

在爱奥尼亚4号上,这对我很有效:

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

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

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

听起来很正常。当没有可导航回的页面时,您希望浏览器去哪里?在UI中使用“返回”链接不是很明确,你能用一个链接替换它吗?该链接可以将用户带到一个可以充当“父屏幕”的屏幕上?例如,如果用户正在查看特定项目,则链接可以将他们带到项目列表;如果它们位于菜单分支的深处,链接可以将它们带到父菜单项,等等。我可以这样做,但是有没有办法检测反向链接是否会转到其他主机或主机名?我并不总是希望导航返回到仪表板,有时它们会从另一个页面跳转。我理解。[CanDeactivate]()允许您在离开路由之前运行一些代码,但我担心它只在从一个角度路由导航到另一个角度路由时有效,而不是从一个路由导航到一个外部URL。我会使用简单的JS。你可以用或收听URL的更改并做出相应的反应。@AngularFrance我想你可能是对的,我会写一个服务来做到这一点,而不是AngularFrance。是的,这就是我正在做的,我在问题中写的。。。我正在寻找一种不会意外退出应用程序的方法。您也不需要在此处绑定goBack方法,您可以直接访问模板中的位置服务。是的,在html中使用:
Back
,但将
public\u location:location
我不知道为什么会被否决。从技术上讲,这是可行的。。。即使它不是首选方法。这正是@angular/common中位置服务的back()方法在幕后所做的,通常情况下,当您使用@angular/platform浏览器模块时。角度法的优点是它更通用,也适用于角度法支持的其他平台。
import { Location } from '@angular/common';

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

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