Eli
Eli

Reputation: 768

Firebase Retrieve Data and return as array of type - my solution

I have recently started moving my iOS Application to also be a web app. I don't know if this implementation is correct. It works, but if someone could please let me know if it is correct.

Here is the function in my LicenceService:

get retriveLicences():Licence[] {

const licences: Licence[] = [];

this.afDatabase.list(this.basePath).valueChanges().subscribe((snapshot) => {
  snapshot.forEach(element => {

    const licenceObject = <any>element

    licences.push(
      new Licence(
        licenceObject.name, 
        licenceObject.logoUrl, 
        licenceObject.maxUsers, 
        licenceObject.currentUserCount, 
        licenceObject.startDate, 
        licenceObject.endDate
      )
    );
  });
});

return licences
}

Upvotes: 1

Views: 1314

Answers (1)

Tsortanidis Christos
Tsortanidis Christos

Reputation: 707

Using rxjs operators, you can "transform" the snapshot before subscribing to it:

getLicences(): Observable<Licence[]> {
  return this.afDatabase
  .list(`/whatever`)
  .valueChanges()
  .map(licenceObjects => {
    return licenceObjects.map(licenceObject => new Licence(
      licenceObject.name, 
      licenceObject.logoUrl, 
      licenceObject.maxUsers, 
      licenceObject.currentUserCount, 
      licenceObject.startDate, 
      licenceObject.endDate
    ));
  })
}

However, if you create an interface with the exact variable names you have in your database, your life can become a lot easier cuz angularfire2 transforms it for you:

interface Licence {
  name: string;
  logoUrl: string;
  maxUsers: number;
  currentUserCount: number;
  startDate: number;
  endDate: number;
}

getLicences(): Observable<Licence[]> {
  return this.afDatabase.list<Licence>(`/whatever`).valueChanges();
}

So now in your component you can get the observable from the service and unwrap it with the async pipe or whatever way makes more sense to your app. I hope this is helpful!

Upvotes: 5

Related Questions