【问题标题】:Get data and make it variable from firebase从 firebase 获取数据并使其可变
【发布时间】:2020-10-20 01:18:23
【问题描述】:

我正在尝试从当前用户获取数据,例如公司:“ZeroMax”,然后将此数据分配给全局变量。 并使用此变量来阐明 firebase 的路径。我希望你能通过查看我的代码来理解我的问题。一切正常,除了分配

this.comp = user['company'];

这是我的 drivers.service.ts 文件:

export class DriversService {

  user: User;
  comp = '';
  constructor(private db: AngularFirestore, private auth: AuthService, private afAuth: AngularFireAuth) { }

 getUsers() {
  return this.auth.user.pipe(
    take(1),
    map(user => {
      //  user['company'];
      this.comp = user['company'];
      return user['company'];
    })
  )
 }

  findUser(value) {

    if (this.comp.length <= 0) {
      return this.getUsers().pipe(map(user => {
      this.comp = user;
      console.log('Bye', this.comp);
      return this.comp;
      }));
    }

    let email = this.db.collection(`companies/${this.comp}/users`, ref => ref.where('email', '==', value)).valueChanges({ idField: 'id' }).pipe(
      take(1)
    );
    let name = this.db.collection(`companies/${this.comp}/users`, ref => ref.where('name', '==', value)).valueChanges({ idField: 'id' }).pipe(
      take(1)
    );
    return [email, name];
  }
}

这是我的 add-driver.page.ts 文件:

export class AddDriverPage implements OnInit {
 
  users = [];
  participant = '';
  form: FormGroup;

  constructor(private driverService: DriversService, private loadingCtrl: LoadingController, private auth: AuthService) { }

  ngOnInit() {
    
  }

  addDriver() {
    const obs = this.driverService.findUser(this.participant);

    forkJoin(obs).subscribe(res => {
      if (!res || !res.length) {
        return console.log('Got undefined');
      }
      for (let data of res) {
        if (data.length > 0) {
          this.users.push(data[0]);
          //console.log(res);
        }
        console.log(res);
      }
      console.log('it works:', this.participant)
      this.participant = '';
    }, error => {
   console.log('Here you got an error: ', error);
});
  }
}

【问题讨论】:

    标签: angular typescript firebase ionic-framework google-cloud-firestore


    【解决方案1】:

    不是在哪里访问this.comp变量,而是何时访问它。当您的 this.db.collection(companies/${this.comp}/users`` 现在运行时,this.comp = user 尚未运行。

    任何需要访问数据库数据的代码都需要在数据可用时执行的回调中。

    例如:

    if (this.comp.length <= 0) {
      return this.getUsers().pipe(map(user => {
        let email = this.db.collection(`companies/${user}/users`, ref => ref.where('email', '==', value)).valueChanges({ idField: 'id' }).pipe(
          take(1)
        );
        let name = this.db.collection(`companies/${user}/users`, ref => ref.where('name', '==', value)).valueChanges({ idField: 'id' }).pipe(
          take(1)
        );
        return [email, name];
      }));
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-26
      • 2017-04-21
      • 1970-01-01
      • 1970-01-01
      • 2017-10-23
      • 2020-05-28
      • 2019-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多