Angular Observable list preproccess

255 views Asked by At

I have an Angular12 application and I get my data from a Firebase Realtime DB using AngularFire. Since I will need my data in different places in my code I want my DAO service to get the firebase Observable list and do I little preprocessing in them (convert string dates to Date objects). If I do this preprocess then I lose the subscription ability and now my app is not getting the benefits of realtime data. So I want to make that preprocess return an Observable list, but I can't figure out how.

My code:

FantaroiDAOService

  private list = this.db.list<Fantaros>('fantaroi')

  constructor(private db: AngularFireDatabase){}

  public getIpir() {
    return this.list.valueChanges();
  }

AppComponent

  ngOnInit(): void {
    let fantaroi: Fantaros[] = [];
    this.dao.getIpir().subscribe(f => {
      fantaroi = f.map(f => {
        const soc = f.soc.map(date => new Date(date))
        const dishes = f.dishes? f.dishes.map(date => new Date(date)) : []
        const off = f.off.map(date => new Date(date))
        return new Fantaros(f.name, soc, dishes, off);
      })
// other Component related code.
});
}

fantaroi is the list I want to monitor for changes and then use it to update my view. Is there a way to do this? Or do I have to copy paste the code that parses to Date object every where I use that list?

1

There are 1 answers

1
Octavian Mărculescu On BEST ANSWER

You should be able to use pipe and apply the transformations using the map operator:

public getIpir() {
  return this.list.valueChanges().pipe(
    map(fantaroi => fantaroi.map(f => {
      const soc = f.soc.map(date => new Date(date))
      const dishes = f.dishes? f.dishes.map(date => new Date(date)) : []
      const off = f.off.map(date => new Date(date))
      return new Fantaros(f.name, soc, dishes, off);
    })
  );
}