更改路线时重新加载Angular 2 App [英] Angular 2 App Reloading on Route Change

查看:61
本文介绍了更改路线时重新加载Angular 2 App的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有以下路线的angular 2应用程序:

I have an angular 2 app with the following routes:

@RouteConfig([
new Route({ path: '/', component: Home, name: 'Home', useAsDefault: true}),
new Route({ path: '/employees', component: ViewEmployees, name: 'ViewEmployees'}),
new Route({ path: '/employees/add', component: AddEmployee, name: 'AddEmployee'}),
])

除其他外.当我通过以下方式更改路线时:

among others. When I change routes in the following way:

<a [routerLink]="['ViewEmployees']">View Employees</a>

没有问题.我可以通过这种方式从主页或AddEmployee路由中更改路由.当我处于AddEmployee路由并尝试以编程方式更改路由时,就会出现问题:

There are no issues. I can change routes in this way from either the home page or the AddEmployee route. The issue comes when I'm in the AddEmployee route and try to change routes in a programmatic way like this:

import {Router} from 'angular2/router';
...
constructor(private _router:Router) {}
...
navigate() {
    this._router.navigate(['ViewEmployees']);
}

它不起作用.它会将我发送到ViewEmployees视图,然后重新加载整个应用程序.如果我从Home组件执行相同的程序化路线更改,则不会有任何问题.该应用程序不会重新加载.

it doesn't work. It sends me to the ViewEmployees view and then reloads the entire app. If I do that same programmatic route change from the Home component I don't have any issues; the app doesn't reload.

有没有人知道为什么在这种情况下会这样做?我需要它来工作,以便我可以保存添加的员工,然后返回到员工列表视图.

Does anyone have any ideas why it would do this in just this one case? I need it to work so that I can save the employee that's added and then go back to the employee list view.

提前感谢您的帮助!

推荐答案

您是否从< form> 标记内调用 navigate()?

我遇到了同样的问题.在Angular2s GitHub上存在描述此行为的一些问题,但由于它们属于旧路由器,因此已全部关闭.当您在由表单内的提交按钮调用的函数内使用 router.navigate()时,似乎发生页面重新加载.这可能导致浏览器在URL末尾附加?并重新加载.

I had the same Problem. There exist some issues describing this behavior on Angular2s GitHub but they are all closed because they belong to the old router. The page reload seems to occur when you use router.navigate() inside a function called by a submit button inside a form. This can cause the browser to append a ? at the end of the URL and reload it.

解决方案非常简单:只需在 navigate()函数的末尾返回false .这样可以防止Bowser在提交表单时使用其默认操作.通常,角度会阻止这种默认行为,但奇怪的是在这种情况下不会.

The solution is very simple: Just return false at the end of your navigate() function. This prevents the bowser to use it's default action when submitting forms. Usually angular stops such default behavior but strangely not in this case.

这篇关于更改路线时重新加载Angular 2 App的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆