Waiting for asynchronous code before populating array

  angular, asynchronous

Trying to get templates with their id‘s, but I’m having trouble coding it so that it waits for the return of the templates. See code below.
I know that I need to somehow wait for getTemplateName before populating my array, but asynchronous code is very difficult for me at the moment.

TS

  templates: any = [];

  ngOnInit() {
    this.user = this.userService.getUser();
    this.syncService
      .getSyncDoc(this.user._id)
      .then(
        (res) =>
          (this.templates = res.Templates.map((template) => {
            console.log(this.templates);
            return this.templateService.getTemplateName(template);
          }))
      );
  }

template service

  getTemplateName(templateId: string): Promise<any> {
    const selector = {
      Type: 'template',
      _id: templateId,
    };
    return this.dbService.find(selector).then((result: any) => {
      console.log(result.docs[0]);
      return result.docs[0];
    });
  }

html

      <ion-item *ngFor="let template of templates">
        <ion-label>{{ template.Template_code }}</ion-label>
        <ion-radio slot="start" value="{{ template._id }}"></ion-radio>
      </ion-item>

Console
Console

App
App

Source: Angular Questions

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.