Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to "wait" for a sync method to complete

I am making a context menu, and in this menu, I am using a key for translation.
I would like to "wait" for this method to finish, before moving on, and display the context menu on my page only when I am certain, that the translation files have already been loaded.

So, here is what I have tried.

contextMenuContent: {
  [key: string]: ContextMenuEntries;
};

constructor(private translationService: TranslationService) {
}

async ngOnInit() {
  this.contextMenuContent = await this.makeContextMenuEntries();
}

async makeContextMenuEntries() {
  return {
    editContextMenuEntry: {
      icon: 'edit',
      text: this.t('edit_contacts'),
      action: () => {}
    }
  };
}

t<T = string>(key: string, param?: object): T {
  return this.translationService.translate(`${TRANSLATION_KEY}.${key}`, param);
}

It is working, but I am looking for a better solution, and I really want to avoid marking ngOnInit as async. How can I improve my code?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

By default, angular will wait for all the SYNC functions in ngOnInit to finish.

You can do a quick demonstration by running:

ngOnInit(){
    let a = '';
    for (let i = 0; i < 10000000; i++) {
      a += i.toString();
    }
}

You will see that the component will be displayed only after a few seconds, the time for the functions in ngOnInit to finish.

So in your case, if the translation doesn’t exist, there aren’t too many solutions:

  • Display nothing because the translation service will never get the solution. No async and await are required because all are SYNC.

    ngOnInit() {
        this.contextMenuContent = this.makeContextMenuEntries();
    }
    
      makeContextMenuEntries() {
       return {
         editContextMenuEntry: {
           icon: 'edit',
           text: this.t('edit_contacts'),
           action: () => {}
         }
       };
    }
    
    t<T = string>(key: string, param?: object): T {
       return this.translationService.translate(`${TRANSLATION_KEY}.${key}`, param);
    }
    
  • Change your translate method for a promise so it would wait the translation in an async way.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading