等待Firestore数据,然后再调用视图

时间:2018-09-28 09:25:06

标签: angular ionic-framework google-cloud-firestore wait subscribe

无论何时启动我的应用程序,我都希望从firestore中获取用户数据。因此,在我的app.component.ts中,我有:

constructor(private platform: Platform, ..., private auth: AuthService, private firebaseServie: FirebaseService, private sessionData: SessiondataProvider) {

    //Here i call a function that I have in a service:
    if(this.sessionData.currentUser == undefined || this.sessionData.currentUser == null || this.sessionData.currentUser == ""){
      this.firebaseServie.setUserData(user.email);
    }
    //And then I start the ProfilePage View:
    this.rootPage = ProfilePage;

服务functipn setUserData调用了一个异步请求到Firestore:

  setUserData(email) {
    this.userCollection = this.afs.collection('users', ref => ref.where('email', '==', email));
    this.userCollection.valueChanges().subscribe((item => {
      this.users = item;
      this.sessionData.currentUser = this.users[0].username;
    }));
  }

因此,服务功能设置了全局变量currentUser。在app.component.ts中,我要确保在启动currentUser视图之前已设置ProfilePage变量。我该怎么办?

2 个答案:

答案 0 :(得分:0)

您可以借助RxJS Observable从同步代码转换为异步代码。

private asyncCode: Subject = new Subject<any>();
public asyncCode$: Observable = this.asyncCode.asObservable();

setUserData(email): void {
    this.userCollection = this.afs.collection('users', ref => ref.where('email', '==', email));
    this.userCollection.valueChanges().subscribe((item => {
      this.users = item;
      this.sessionData.currentUser = this.users[0].username;
      this.asyncCode.next(true);
    }));
  }

this.asyncCode$.subscribe((status)=>{
    this.rootPage = ProfilePage;
});

答案 1 :(得分:0)

我使用SpinnerDialog解决了这个问题。在GOARCH="amd64" GOBIN="" GOCACHE="/Users/amitsharma/Library/Caches/go-build" GOEXE="" GOHOSTARCH="amd64" GOHOSTOS="darwin" GOOS="darwin" GOPATH="/Users/<username>/Desktop/gocode" GORACE="" GOROOT="/usr/local/go" GOTMPDIR="" GOTOOLDIR="/usr/local/go/pkg/tool/darwin_amd64" GCCGO="gccgo" CC="clang" CXX="clang++" CGO_ENABLED="1" CGO_CFLAGS="-g -O2" CGO_CPPFLAGS="" CGO_CXXFLAGS="-g -O2" CGO_FFLAGS="-g -O2" CGO_LDFLAGS="-g -O2" PKG_CONFIG="pkg-config" GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/0d/pkfrs5cj0v57xgsnwvb2kb580000gn/T/go-build028697826=/tmp/go-build -gno-record-gcc-switches -fno-common"

的回调中调用SpinnerDialog的hide()函数