0

On my Angular page, I have set up routing using <router-outlet></router-outlet>. When an user first loads the page (like the home page), I send a total of 3 requests:

  1. /api/GetCategories
  2. /api/GetRecentPosts
  3. /api/GetAllPosts

When I click on a post, only one request is sent: /api/GetPost/{id}

Because of this, if I update my categories or create a new post, the user won't see them until a page reload (F5 for example).

I know a proper way to solve this: Create a socket connection between my server and the client, and each time a new post has been made, it's automatically updated on the page. No caching, no random interval GET requests, and so on. An elegant solution. However, it's also the most painful in terms of maintenance and so on.

What other options do I have? Send the request every page load, but cache the result on my backend? Create some kind of token that dies after a certain amount of time, and then it sends a request to update the categories and posts? Something third?

MortenMoulder
  • 6,138
  • 11
  • 60
  • 116
  • Maybe implement a /api/Check4Updates(lastTimeChecked) that is on an Interval Observable? And when this returns true, then make sure the updates of the content happen? – Charlie V Jun 08 '22 at 12:40
  • @CharlieV That's not very elegant, though. I would have to add a cache to my backend (because I don't want to ask the DB every time), and at that point, I might as well keep the cache updated with the categories and posts, and then just return those. – MortenMoulder Jun 08 '22 at 12:54
  • A socket implementation is the nicest way, as you have stated already. Unfortunately I do not know of other Push mechanisms that achieve the same, without the maintenance burden. – Charlie V Jun 08 '22 at 13:44
  • @CharlieV I was hoping someone had a way, in Angular, to send the request when changing routes, but only after x amount of time has passed. Something I can mark my specific requests with. – MortenMoulder Jun 08 '22 at 14:02

1 Answers1

1

To elaborate on your suggestion in the comments:

If the view changes you can read data after some time has passed or skip the reading if that just happened. To achieve this you have to subscribe to NavigationEnd events in one of your top components:

...
constructor(private router: Router) {

  router.events.pipe(
    filter(event => event instanceof NavigationEnd)
  ).subscribe((event) => {
    this.doTimedReading(event.url);
  });
...
doTimedReading(url){
// Check with your services for the last time data ingress took place.
// Update what is needed based on the view presented
}

Whenever a route is (successfully) changed the doTimedReading is called. Based on what your strategy is you can read the parts or all data.

Based on this discussion: How to detect a route change in Angular?

Charlie V
  • 980
  • 1
  • 6
  • 12