javascriptangularionic-frameworkionic4ionic5

Run a component function every time its rendered


I've got an Ionic Angular app that calls an API every time the view changes and stores the value in ionic storage.

Every page has a 'header' component that is supposed to display this value from storage.

Inside ngOnInit(){} I fetch the value from storage and the value updates. However, it only does it once per page view. So if I view the homepage, for example, go to page 2, and back to the homepage, the code won't re-execute.

I imagine this is because the page doesn't actually unmount when you change the view, and therefore has no reason to 're-construct'.

constructor(){} only runs on the first construct for that view

ngOnInit() {} only runs the first init for that view

ionViewDidLoad() {} doesn't run because its not a view and that's an ionic page life cycle hook

I'm basically looking for a way to call an API, store the value in ionic storage, and on every page change, update the value in the header.

I've been thinking this might be achievable with Observables, but I'm not sure how this would work with ionic storage.

Or even get the value from storage in the view using one of the ionic view lifecycle hooks and pass it into the header as a prop, but that just seems messy.

The reason I'm using storage is that the balance gets used elsewhere and not just in the header and it saves me making the call multiple times if it's just available in storage.

Any recommendations appreciated

export class HeaderComponent {
  balance = 0.00;

  constructor(
    private storage: Storage,
  ) { }

  async ngOnInit() {
    this.storage.get('balance').then(data => {
      this.balance = data;
    });
  }
}

Solution

  • If you're positive that ngOninit in HeaderComponent is only firing once, then that means that it's not being destroyed between route changes. That would make sense if your component is present in all of your views.

    I would not use local storage to distribute your application state to your app components. If your app state is relatively simple, then observables are the way to go. Create a service that holds the state of your application in an observable. Every time you fetch data from the API, push the new data to the observable. Then in your HeaderComponent subscribe to the observable in the ngOnInit hook so that your component data can be automatically synced to the application state any time there is a change.