Angular 页面刷新的两种方法

1,915 阅读1分钟

Angular 开发的单页面应用,有一种功能需求,比如切换了某个全局变量,需要当前路由页面刷新一下。

那么有两种方式:

// 第一种
window.location.reload(); // JS 自带的刷新方法

// 第二种
get route() {
    return this.injector.get(Router); // 注册 Router 服务
}

const curentUrl = this.route.url;  // 获取当前页面的路由地址
// `client` 这个路由要根据你项目的默认根路径修改
// skipLocationChange 这个配置一定要配置,不然会发生页面跳转的效果
this.route.navigateByUrl(`client`, { skipLocationChange: true }).then(() => {
  this.route.navigateByUrl(curentUrl); // 重新导航到当前页面路由
});

优劣

第一种方法,会出现浏览器刷新页面的效果。简单粗暴,略显突兀。

第二种方法,显得就比较温柔,没有页面大刷新的效果。

总结

以上,希望对你有帮助。点赞是鼓励。