Angular2 router.navigate 刷新页面 [英] Angular2 router.navigate refresh page

查看:46
本文介绍了Angular2 router.navigate 刷新页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是路由和组件的样子:

<块引用>

routes.config

导出常量路由:RouterConfig = [{ path: 'users', 组件: UsersComponent, canActivate: [AuthGuard] },{ path: 'users/new', 组件: NewUserComponent },];

<块引用>

new-user.component

 addField(newName: string){this.items.push({名称:新名称,})this._router.navigate(['/users'])

Angular2 是否应该刷新 router.navigate 上的页面?

还有什么可以代替 router.navigate 来避免任何页面刷新?

证明如下:

解决方案

您可能正在单击事件中调用 router.navigate 函数.

保存功能类似于

save() {//做东西this._router.navigate(['/users', { id: userId } ]);}

这适用于 IE11 和 Edge 浏览器,但会在 Chrome 中重新加载应用程序.

这是因为按钮元素中缺少 type,如果按钮位于

内,Chrome 将使用提交"因为它是默认值.点击按钮时导致表单提交.

在使用 button 元素时,最好总是设置 type参见此处:

因此将 HTML 更改为

将使其适用于所有 3 个浏览器.

我之前的解决方案也有效,(通过返回 false 会阻止默认操作.也就是提交表单)但我认为上面的解决方案是首选.

<块引用>

过时的答案,但为后代保留:

This is how the routes and component look like:

routes.config

export const routes: RouterConfig = [
   { path: 'users', component: UsersComponent, canActivate: [AuthGuard] },   
   { path: 'users/new', component: NewUserComponent },    
];

new-user.component

 addField(newName: string){
        this.items.push({ 
          name: newName,
      })
      this._router.navigate(['/users'])

Is Angular2 supposed to refresh the page on router.navigate?

What else to use instead of router.navigate to avoid any page refresh?

Here is the proof:

解决方案

You are probably calling the router.navigate function inside a click event.

<button class="btn btn-default"
    (click)="save()">Save</button>

And the save function being something like

save() {
    //Do stuff
    this._router.navigate(['/users', { id: userId } ]);
}

This works on IE11 and Edge browsers, but would reload the application in Chrome.

This is because of a missing type in the button element, if the button is inside a <form></form> Chrome will use 'submit' as it's default value. Causing a form submit when the button is clicked.

It's preferred to always set a type when using the button element See here:

So changing the HTML to

<button class="btn btn-default" type="button"
        (click)="save()">Save</button>

Will make it work on all 3 browsers.

My previous solution also works, (By returning false it would prevent the default action. a.k.a. submitting the form) but I think the above one is preferred.

Obsolete answer but kept for posterity:

<button class="btn btn-default"
        (click)="save(); false">Save</button>

这篇关于Angular2 router.navigate 刷新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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