Arash
Arash

Reputation: 12415

how to handle observables in angular firebase

I have a conceptual question. I am using angularfire2 with angular 6, and I am not sure how to handle all the observables.

Most of my pages need user, which is an observable, then they might need a query parameter, which is another observable. So I have some code doing like

zip(
  this.route.paramMap,
  this._auth.user
)
  .pipe(
    switchMap((val: [ParamMap, User]) => {
      this.url = `/users/${val['1'].uid}/dto/${val['0'].get('id')}`;
      return this._fireStore.doc(this.url).snapshotChanges();
    }),
    switchMap((val: Action<DocumentSnapshot<any>>) => {
      let data = val.payload.data();
      return of(Dto.fromPayLoad(val.payload.id, data));

    })).subscribe(it => this.model = it);

I feel like it is overly complicated. What is the stablished patterns here? Can someone point me to best practises.

Upvotes: 0

Views: 126

Answers (1)

Robin Dijkhof
Robin Dijkhof

Reputation: 19278

First of all, that second switchMapis not needed and can be shorter:

map(val -> Dto.fromPayLoad(val.payload.id, val.payload.data()))

Next, I would put my user in some global service and create a service and method for your data fetch.

@Injectable()
export class MyDataProvider{
  constructor(private globalService: GlobalService){} //Global service that contains the user.

  public getMyData(id: string): Observalbe<MyData> {
    return this.globalService.user.pipe(
      switchMap(user -> this._fireStore.doc(`/users/${user.uid}/dto/${id}`).snapshotChanges()),
      map(val -> Dto.fromPayLoad(val.payload.id, val.payload.data()))
    );
  }
}

Now call this in you component:

this.route.paramMap.pipe(
  switchMap(param -> this.myDataProvider.getMyData(params.get('id')))
).subscribe(...)

Upvotes: 1

Related Questions