Angular 2 Firebase Observable to promise doesn't return anything

后端 未结 1 1965
一向
一向 2020-12-29 09:02

I\'m currently working on an Angular 2 project with AngularFire2 and I\'m trying to convert a FirebaseListObservable to a Promise. I know that it doesn\'t make much sense si

相关标签:
1条回答
  • 2020-12-29 09:38

    The problem is that the toPromise operator converts the observable to a promise that resolves to the observable's final value. That means the observable must complete before the promise resolves.

    In AngularFire2, list and object observables don't complete; they re-emit whenever the database changes.

    You can solve the problem using the first operator, which takes the first emitted value and then completes the composed observable:

    import 'rxjs/add/operator/first';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/toPromise';
    ...
    return this._af.database
      .list('users')
      .map(users => {
    
        let exists = false;
        users.forEach(user => {
          if (user.name.toLowerCase() === name.toLowerCase()) {
            console.log('Name already exists!');
            exists = true;
          }
        });
        return exists;
      })
      .first()
      .toPromise();
    
    0 讨论(0)
提交回复
热议问题