【问题标题】:Wait for firestore data before calling view在调用视图之前等待 Firestore 数据
【发布时间】:2018-09-28 09:25:06
【问题描述】:

每当我的应用启动时,我都想从 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;

服务函数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 中,我想确保在启动ProfilePage 视图之前已经设置了currentUser 变量。我怎样才能做到这一点?

【问题讨论】:

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


    【解决方案1】:

    我使用 SpinnerDialog 解决了这个问题。在subscribe的回调中调用SpinnerDialog的hide()函数

    【讨论】:

      【解决方案2】:

      您可以在 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;
      });
      

      【讨论】:

      • Type 'Subscription' is not assignable to type 'Observable&lt;any&gt;'. Property '_isScalar' is missing in type 'Subscription'.
      • 我们不能从订阅返回 observable。您可以使用主题
      • Generic type 'Subject&lt;T&gt;' requires 1 type argument(s). Oberservable 出现同样的错误
      • A function whose declared type is neither 'void' nor 'any' must return a value.
      猜你喜欢
      • 2021-07-12
      • 2018-09-05
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多