0

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.

1
  • Huum, and why exactly it is down voted?! Commented Jul 3, 2018 at 14:54

1 Answer 1

1
+50

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(...)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.