为最终可观察到的对象定义undefined,该对象应通过switchMap

时间:2019-03-30 12:04:59

标签: angular typescript firebase firebase-authentication

我希望有人可以帮助我。我对打字稿和angular / firebase尚不陌生,我需要一些帮助。

我有一个auth.service文件,该文件查看用户的登录状态。确认用户已登录后,它将查看其自定义声明。如果存在“经纪人”的自定义声明,则它将查找firestore经纪人集合以检索该经纪人的信息,包括在firestore中分配的角色。

我了解,我可能可以直接使用自定义声明进行基于角色的工作,但是我希望能够检索Firestore数据以获取其他信息等。

无论如何,由于某种原因,我对最后的可观察对象一直不确定,该对象应该保存在user $变量中。

我假设这与来自Firestore的响应延迟有关。虽然我到处都使用async await语句。请参考此消息中的代码。

有人可以帮我这个忙,并告诉我发生了什么事吗?我将非常感谢。

另一件事确实很奇怪,就是switchMap内try {}块中的if语句不断执行并返回多次(三)。此消息后,请参阅我的屏幕截图。

不知道我在做什么错。非常感谢您提供任何帮助。

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import * as firebase from 'firebase/app';
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestoreDocument, AngularFirestore } from 'angularfire2/firestore';
// import { User } from 'firebase';
import { User } from '../models/User.model';
import { switchMap, first, take } from 'rxjs/operators';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
import { useAnimation } from '@angular/animations';
import { Observable } from 'rxjs';
import { of } from 'rxjs';


@Injectable({
  providedIn: 'root'
})
export class AuthService {

  // user: User;
  user$: Observable<any>;
  isBroker: boolean;

  error: any;

  constructor(public afAuth: AngularFireAuth, public router: Router, private afs: AngularFirestore) {
    /****
     * If the user is logged in, we add the user's data to the browser's local storage; otherwise we store a null user
    *****/

  // const user = this.isLoggedIn();
  // console.log(user);

  // afAuth.auth.signOut();
  // console.log('I am out');

   this.user$ = this.afAuth.authState.pipe(switchMap(async user => {
    /**
     * If a logged in user exists, check if the custom claim is broker, then look up in brokers collection
     * else check in clients collection
     */
    try {
      if (user) {
       //console.log(this.user$);
       console.log(user.email);
       await user.getIdTokenResult().then(async idTokenResult => {
          if (idTokenResult.claims.broker) {
            console.log('broker logged in');
            const brokerData$ = await this.afs.doc<User>(`brokers/${user.email}`).valueChanges();
            brokerData$.subscribe(broker => {
              console.log(broker);
            })
            return brokerData$;
          } else if (idTokenResult.claims.user) {
            return this.afs.doc<User>(`clients/${user.email}`).valueChanges();
          }
        });
          } else {
              console.log('no user');
              return of(null);
          }
    } catch (e) {
      console.log(e);
    }
  }));
  this.user$.subscribe(user => {
    console.log(user);
  })
  }

async getBrokerData(uid) {
  console.log(uid);
  const brokerData$ = await this.afs.doc<User>(`brokers/uid`).valueChanges();
  brokerData$.subscribe(broker => {
    console.log(broker);
  })
  // console.log(brokerData$);
  return brokerData$;
}

  /***
   * Method to login users with email and password
   */

  async emailLogin(email: string, password: string) {
    try {
      await this.afAuth.auth.signInWithEmailAndPassword(email, password);
      this.router.navigate(['/dashboard']);
    } catch (e) {
      // alert('Error! ' + e.message);
      this.error = e.message;
    }
  }

  async loginGoogle() {
    try {
      await this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider()).then(
        (success) => {
          this.router.navigate(['/dasboard']);
        });
    } catch (e) {
      alert('Error!' + e.message);
    }
  }

  async loginFb() {
    try {
      await this.afAuth.auth.signInWithPopup(new firebase.auth.FacebookAuthProvider()).then(
        (success) => {
          this.router.navigate(['/dasboard']);
        });
    } catch (e) {
      alert('Error!' + e.message);
    }
  }

  async logout() {
    await this.afAuth.auth.signOut();
    //localStorage.removeItem('user');
    this.router.navigate(['']);
  }

  // get isLoggedIn(): boolean {
  //   const user = JSON.parse(localStorage.getItem('user'));
  //   return user !== null;
  // }

  async isLoggedIn() {
    return await this.afAuth.authState.pipe(first()).toPromise();
  }

  get getAuthState() {
    return this.afAuth.authState;
  }


}

observable用户$应该从Firestore加载数据。但是由于某种原因,它总是以不确定的形式出现。

我在控制台中看到的响应如下所示。

How my console looks at the moment

0 个答案:

没有答案