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

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

问题描述

这是路线和组件的外观:

This is how the routes and component look like:

routes.config

routes.config

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

new-user.component

new-user.component

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

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

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

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

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

以下是证明:

推荐答案

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

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

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

保存功能类似于

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

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

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

这是因为按钮元素中缺少type,如果按钮位于<form></form>内部,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.

使用button元素时最好始终设置type 在此处查看:

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

因此将HTML更改为

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

将使其在所有3种浏览器上均可使用.

Will make it work on all 3 browsers.

我以前的解决方案也可以(通过返回false可以阻止默认操作,也就是提交表单),但我认为上述方法是可取的.

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天全站免登陆