angularjs 哪种方法是处理观察到的依赖关系的正确方法?

laawzig2  于 2023-03-22  发布在  Angular
关注(0)|答案(1)|浏览(128)

我的项目使用Angular 15和@angular/fire ^7.5.0。
我有一个对Firestore数据库进行一些调用的服务,但在执行任何操作之前,我需要从FireAuth通过Observable提供的当前用户恢复一些信息。

import {
  collection,
  Firestore,
  collectionData,
} from '@angular/fire/firestore';
import { AuthService } from '../auth/auth.service';
import { User } from '@angular/fire/auth';

export class DummyDataService {
  userObservable: Observable<User | null>;
  constructor(
    private fs: Firestore,
    private _auth: AuthService
  ) {
    // currentUser$ is an Observable that holds the User data when available
    this.userObservable = this._auth.currentUser$;
  }
  
  // example function
  getAll() {
    // this should be done after the user$ observable is filled with the real User
    const coll = collection(this.fs, `/${user.custom_data}/dummydata`);
    // return the data as an Observable
    return collectionData(coll, { idField: 'id' });
  }
}

所以我在问哪种方法才是处理这种情况的正确方法

n6lpvg4x

n6lpvg4x1#

import {
  collection,
  Firestore,
  collectionData,
} from '@angular/fire/firestore';
import { AuthService } from '../auth/auth.service';
import { User } from '@angular/fire/auth';

export class DummyDataService {
  userObservable: Observable<User | null>;
  private user: User | undefined;
  constructor(
    private fs: Firestore,
    private _auth: AuthService
  ) {
    // currentUser$ is an Observable that holds the User data when available
    this.userObservable = this._auth.currentUser$;
    this.userObservable.currentUser$.subscribe((user) => {
       this.user = user;
    },
    (error) => {
       console.error(error);
    });

  }
  
  // example function
  getAll() {
    if (this.user) {
      // this should be done after the user$ observable is filled with the real User
      const coll = collection(this.fs, `/${user.custom_data}/dummydata`);
      // return the data as an Observable
      return collectionData(coll, { idField: 'id' });
    } else {
      alert('Action not possible. Not logged in');
    }
  }
}

相关问题