Alan S
Alan S

Reputation: 93

How can I convert an array of promises into a simple array?

I have this service that fetch everything from database and this model:

export interface ServerPartner {
  uid: string;
  name: string;
  weight: number;
  logo?: string;
  active?: boolean;
}

export class Partner {
  uid: string;
  name: string;
  weight: number;
  logo?: string;
  active?: boolean;

  constructor(serverPartner: ServerPartner) {
    Object.assign(this, serverPartner);
  }
}


getAll$(): Observable<Partner[]> {
    return this.afs.collection<Partner>('partners')
    .valueChanges()
    .pipe(
      map((sPartners: ServerPartner[]) => sPartners
        .map(sPartner => new Partner(sPartner))
        .sort((a: Partner, b: Partner) => a.name > b.name ? 1 : -1)
      )
    );
  }

  getAll(): Promise<Partner[]> {
    return this.getAll$()
      .pipe(take(1))
      .toPromise();
  }

In my component I call the function getAll() like this:

partners: Partner[];

ngOnInit() {
  this.partners = this.partnerService.getAll();
}

but I get the following error:

Type 'Promise<Partner[]>' is missing the following properties from type 'Partner[]': length, pop, push, concat, and 26 more.ts(2740)

How can I convert an array of promises into a simple array?

Upvotes: 0

Views: 401

Answers (2)

Mortaza Ghahremani
Mortaza Ghahremani

Reputation: 392

Just use subscribe after get method:

this.partnerService.getAll().subscribe(result => {
          this.partners = result ;
        });

Upvotes: 1

tano
tano

Reputation: 2817

async ngOnInit() {
  this.partners = await Promise.all(this.partnerService.getAll());
}

Upvotes: 3

Related Questions