2

I've tried looking for solutions and most people suggest having a resolver, but in my case I think it would be too complicated so I really need advice on how to do this.

Overview of the app: I have a platform that allows users to login (URL/app/login), and once they are successfully logged in, they will be redirected to the dashboard (URL/app/dashboard). When the user logs in, their token will be stored in the cookies and I'm fetching multiple data related to this user. This will be stored in the component dataServices. Everything works fine, but the problem is when the user reloads the browser, dataServices will be filled asynchronously and hence some components that depend highly on dataServices will be initialized first before the dataServices are filled. One approach that I can think of is to use an observer in "dataServices" and wait until the data are filled, then notify the subjects.

Does anyone have any suggestions on how to do this in angular? (I'm particularly new to angular, sorry)

georgeawg
  • 48,608
  • 13
  • 72
  • 95
  • If you are new to Angular then make sure you get a good understanding of RxJs before you jump in. I wish somebody gave me this advice before I started my Angular journey. Angular is built upon RxJs and having a good understanding will change the way you write code. – Adrian Brand Dec 06 '19 at 03:57

1 Answers1

1

The way I do this is to have router outlets that don't render while data is loading

In the higher level component

<app-spinner *ngIf="loading$ | async else loaded"></app-spinner>
<ng-template #loaded>
  <router-outlet></router-outlet>
</ng-template>

This way your child component that rely on the parent data being loaded don't render until the data is loaded.

You can have a read of this pattern I use in this article I wrote. https://medium.com/@adrianbrand/angular-state-management-with-rxcache-part-2-12de225e4de0

Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
  • The problem is, the data in dataServices is used in ngOninit() in many components so I'm not sure if this will solve my issue – Andi Perkaa Dec 06 '19 at 04:03
  • Put the loading spinner in your app.component.html have a loading$ observable on the dataServices that you assign to the loading$ observable on the component. This way none of the components will render until the data in dataServices is ready. – Adrian Brand Dec 06 '19 at 04:17