问题: angular 从子状态回到当前的父级状态的时候,父级状态不会重新初始化。

https://github.com/angular-ui/ui-router/issues/2992

原文:https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2

------------------------------------------------

Back in the days of AngularJS you were able to reload a route even if you were already viewing it. For example, clicking on the home option of a menu when you are already viewing the homepage would refresh the homepage. This was useful for a number of reasons, but most importantly for UX. Users expect to be able to click on a page menu item and have the page re-initialise. Setting up this type of reloading in AngularJS was straightforward. You could invoke reload() in your router and away you went.

When Angular 2 was released this feature was not present in the router and there was no easy way to reload the active route. Many people developed “hacky” techniques such as bouncing through a second route in the A -> B -> A sequence, effectively sending you off to a page and back again to trigger the reload. That had the desired effect but was rather inefficient. Another technique that was often suggested was outright reloading the page, which for a single page application is a bad idea.

As of Angular 5.1 there is a supported technique for route reloading. This can now be done using the onSameUrlNavigation
configuration option as part of the built-in Angular router. Unfortunately, the documentation does not make it very clear on how to implement it, so I have documented my approach below.

The first thing you will need to do is set the option within your app.routing.tsif you have one, or the file where your app routing is configured in your particular project.

There are two possible values for onSameUrlNavigation ’reload’ or false. The default value is false, causing nothing to happen when the router is asked to navigate to the active route. We want to set this value to reload. It is worth noting reload does not actually do the work of reloading the route, it only re-triggers events on the router that we then need to hook into.

@ngModule({ imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: ‘reload’})], exports: [RouterModule], })

To determine how those events are actually fired, you need to specify the runGuardsAndResolvers configuration option on your route. This can take one of three values

paramsChange — only fire when route params have changed e.g. where the id in /user/:id changes

paramsOrQueryParamsChange — fire when a route param changes or a query param changes. e.g. the id or the limit property change in /user/:id/invites?limit=10

always — Always fire when the route is navigated

We want to specify always in this case. An example route definition is shown below.

export const routes: Routes = [ {   path: ‘invites’,   component: InviteComponent,   children: [     {       path: ‘’,       loadChildren: ‘./pages/invites/invites.module#InvitesModule’,     },   ],   canActivate: [AuthenticationGuard],   runGuardsAndResolvers: ‘always’, }]

With these two changes your router is configured. The next step is to handle the events that your router will produce within one of your components. To do this you will need to import the Router into your component and then hook into the events of interest. In this example, I have hooked into the NavigationEnd event which is fired once the router has completed its navigation from one route to another. Due to the way we have configured the app, this will now fire even if you try to navigate to the current route.

export class InviteComponent implements OnInit, OnDestroy{
 // ... your class variables here navigationSubscription;
 constructor(   // … your declarations here   private router: Router,  ) {   // subscribe to the router events - storing the subscription so   // we can unsubscribe later. 
   this.navigationSubscription = this.router.events.subscribe((e: any) => {     // If it is a NavigationEnd event re-initalise the component     if (e instanceof NavigationEnd) {       this.initialiseInvites();     }   }); }

 initialiseInvites() {   // Set default values and re-fetch any data you need. }
 ngOnDestroy() {    // avoid memory leaks here by cleaning up after ourselves. If we      // don't then we will continue to run our initialiseInvites()       // method on every navigationEnd event.    if (this.navigationSubscription) {         this.navigationSubscription.unsubscribe();    }  }}

The heavy lifting goes into the initialiseInvites() method, this is where you reset properties to their default values and fetch data from services to get the component back to its initial state.

You need to repeat this pattern across each component that you would like to to reload, being sure to add the runGuardsAndResolvers option to each route in the routing file.

** Updated 05/03/2018 **

Thanks to Changyu Geng and Dennis de Laat for pointing this out in the comments.

I have added an unsubscribe handler in the ngOnDestroy hook in the above example.

As router.events is global, if we do not unsubscribe our event handler on component destruction then it will continue to fire for every NavigationEndevent across our application even when we are not on the invites screen. This is less than ideal because

a) We will be running our event handler for invites even if we are on another screen.

b) Every time we navigate back to invites we will resubscribe to the event. This would cause our initialise function to run n times, where n is the number of times we have landed on the invites page.


If you’ve enjoyed this blog, please take a couple of minutes to check out Gurn and see how it can make you a more productive developer.

---------------------------------------------------------------------------

Ask Question
2

I want to extract only the last event entry of type NavigationEnd from router.events. But somehow I can't find a proper way to do this. Whatever I try the following code snipped is the only way to get access to these objects of interest.

letne:any;router.events.filter(e =>e instanceofNavigationEnd).forEach(e =>{ne =e as NavigationEnd;});console.log('target page: ',ne.urlAfterRedirects);

But do I really have to use .forEach() letting it run though all entries and using then the last entry? Isn't there a better way to handle the events as a kind of array and then say

ne =arrayOfEvents[arrayOfEvents.length-1]

?

I'm getting crazy about it but it seems that I can't see the wood for the trees...

shareedit

  • 1
    Have you looked at using the last operator on observables? reactivex.io/documentation/operators/last.html – Daniel W Strimpel Apr 8 '18 at 20:29
  • Yes, I tried it. But it unfortunately doesn't work in my case as there is no processable return value. – Lynx 242Apr 8 '18 at 20:45
  • 2
    Did you see this article? toddmotto.com/dynamic-page-titles-angular-2-router-events – Vega Apr 8 '18 at 20:49
  • 1
    That's it! This helps a lot. Thank you. – Lynx 242 Apr 8 '18 at 21:00
  • If the events observable never completes then last never does anything. What do you mean by last? YOUmean the last in the group. But the computer can wait 100 years for the stream to close, and that's what last() means to RxJS! So I think actually last() will NEVER return (it possibly might as the page is being unloaded but that's no use). – Simon_Weaver Jan 23 at 22:10

2 Answers

activeoldestvotes

4

Okay, after reading through the posted articles above and rethinking what I really want to achieve I found out that my approach was definitely too complicated. Because actually I only need access to the currently called route. And so I started from scratch and came across this small but very effective solution:

this.router.events.subscribe(value =>{console.log('current route: ',router.url.toString());});

Thanks to all who shared a comment in oder to support me! It helped al lot as I was able to tie up loose ends.

shareedit

add a comment

4

PS. There's a better way to filter using a 'typeguard', you then get the proper type without having to assert it again:

firstChildData$ =this.router.events.pipe(filter((e):e is NavigationEnd=>e instanceofNavigationEnd),map(e =>{// e is now NavigationEnd }

enter image description here

This is actually necessary in strict mode.

转载于:https://www.cnblogs.com/oxspirt/p/11055122.html

Reloading current route in Angular 5 / Angular 6 / Angular 7相关推荐

  1. Angular随记:Angular CLI安装及使用

    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 目录 一.安装 Angular CLI 二.Angular CLI 使用 1.命令总览 2.创建应用 3.启动运行项目 4.创建指定的 ...

  2. 破境Angular(三)Angular构件之模块

    一.知识点 Angular模块核心知识点如下: 1.模块的作用. 2.模块各个元数据的含义和作用 3.模块有哪些分类,分类原则 4.模块的惰性加载机制 5.开发时如何对模块进行规划 二.模块作用 首先 ...

  3. swagger 源代码_我们如何使用swagger代码生成器从Angular 4更新到Angular 5

    swagger 源代码 by Mark Grichanik 马克·格里卡尼克(Mark Grichanik) 我们如何使用swagger代码生成器从Angular 4更新到Angular 5 (How ...

  4. Angular Landing – Material Design Angular App Landing Page

    http://www.yunnut.com/angular-landing-material-design-angular-app-landing-page/ Angular Landing – Ma ...

  5. angular 代码生成器_使用Angular 10构建QR代码生成器

    angular 代码生成器 In this tutorial, we'll learn how to build a QR Codes generator application using the ...

  6. Angular介绍、安装Angular Cli、创建Angular项目入门教程

    场景 Angualr 是一款来自谷歌的开源的web 前端框架,诞生于2009 年,由Misko Hevery 等 人创建,后为Google 所收购.是一款优秀的前端JS 框架,已经被用于Google ...

  7. [Angular 依赖注入详谈] Angular Module Providers几种类型的实现源代码具体位置

    providers: [{ provide: JerrySandBoxService },{ provide: GreetingService, useClass: EnglishGreetingSe ...

  8. angular 加入原生html,Angular HTML绑定

    收到一只叮咚 Angular 2.0.0和Angular 4.0.0 final仅为了安全的内容 constructor(private sanitizer:DomSanitizer){} trans ...

  9. 4 5区别 angular 和_初探Angular的更新机制

    了解Angular组件的渲染及更新机制在Angular应用开发中能让我们的代码更高效及优化应用性能.今天我们就来聊聊Angular的更新机制. 开发过AngularJS应用的同学可能知道一个词,脏检测 ...

最新文章

  1. 微软私有云最佳工作模式
  2. iOS MMDrawerController源码解读(一)
  3. boost::hana::append用法的测试程序
  4. Redis简单案例(四) Session的管理
  5. linux touch权限不够,Linux下的Access、Modify、Change , touch的使用以及权限问题
  6. @Python 程序员,如何最大化提升编码效率?
  7. Inceptor如何访问本地文件
  8. postsql字符串字段转数字用法
  9. js html导出表格数据格式文件格式,js导出excel表格文件带格式
  10. Xshell6、Xftp6【官方免费版】下载
  11. Java8新特性全面
  12. EasyRecovery15可靠的数据恢复软件
  13. Android 车机系统 One Binary 适配白天黑夜的一个方案
  14. [日常] win10系统设置电脑从不休眠睡眠
  15. Pspice仿真实验 例B-1
  16. Centos7.2 Apache根据User-Agent设置访问禁止
  17. c语言解一元二次方程代码,一元二次方程求解程序完整代码
  18. LeetCode题解(1079):活字印刷(Python)
  19. 更改HTML提交按钮的名字
  20. ios 调用 H5页面中含有百度地图,地图不显示

热门文章

  1. 中国绿色PPP项目行业现状及发展建议:投资规模不断扩大,需要改善存在的问题,进一步推动绿色PPP健康发展[图]
  2. 大连八中学2021年高考成绩查询,2021年大连各高中高考成绩排名及放榜最新消息...
  3. 快速学习COSMIC软件规模度量方法
  4. 高数笔记基础篇(更完)
  5. Java图形化GUI界面
  6. VS2017 创建安装项目模板
  7. java 视频压缩_Java 压缩视频(无需安装插件)
  8. js 实现在当前页面打开新窗口
  9. word文档可以打开但显示乱码的完全解决攻略
  10. rono在oracle的作用_ColorOS产品规划总经理爆料预热Reno,这些功能你想要吗?