0
votes

I am performing an operation in angularfire2 where I subscribe to angularfire.auth in order to retrieve the user id for the currently signed in user using the following code:

angularfire.auth.subscribe(auth => {
      this.userId = auth.uid;
      console.log(this.userId);
  }

This works successfully and assigns the uid to the local variable userId.

The problem I am having is when I wish to perform the following code:

let shipObservable = angularfire.database.list('/ships/' + this.userId);

    shipObservable.subscribe(
        value => {
            this.otherObservable = angularfire.database.list('/other/' + value[0].otherId);
            this.otherObservable.subscribe(value => {
                this.address = value[0].$value;
                this.number = value[1].$value;
                this.email = value[2].$value;
                this.name = value[3].$value;
                });
    }).catch((err) => console.log(err));

The issue is that the second piece of code runs before I get the uid back from the first observable. I am aware that these are asynchronous operations and may come back at anytime. But I would like to know is there a way to ensure that the second observable executes after the user id has been assigned to the uid returned by auth.

1
AngularFire returns a promise now.Cory Silva
@CorySilva Which part of it is returning a promise? Was this a recent update?Darragh Murphy
I was looking for the subscribe method and cannot find it... Nor do I remember it. What version are you using? The promise I referenced is described hereCory Silva
As far as I know angularfire.auth is an observable. I am using angularfire 2 version 2.0.0-beta.3-pre2Darragh Murphy
Lol nevermind; I did not notice you were using AngularFire2/ecmascript 6. I should have realized when I saw the subscribe method... duh.Cory Silva

1 Answers

0
votes

I have solved this problem using the switchMap operator which is part of RXJS. In the snippet below I assume that 'afAuth' is a reference to the firebase auth object and 'af' is a reference to the firebase database object.

authState$ = afAuth.authState;
shipObservable$ = authState$.switchMap((auth) => {
    return af.list('ships/' + auth.uid);
});

To use switchMap you need to import the operator:

import 'rxjs/add/operator/switchMap';