Angular 2 Firebase Promise Observed Returns Nothing

I am currently working on an Angular 2 project with AngularFire2, and I'm trying to convert FirebaseListObservable to Promise. I know this doesn't make much sense, since Observables are more useful, but this function will be part of another function in which there are several chains of promises. And I'm not familiar with how to subscribe to Observables in a chain from promises ... The function runs in the service, however it does not seem to return anything. Basically what I want to do is check the Firebase list if an object with a specific name already exists and returns either true or false.

Service

constructor(private _af: AngularFire) { } nameExists(name: string): Promise<boolean> { 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; }).toPromise(); } 

component

 constructor(private _usersService: UsersService) { } check(name) { this._usersService.nameExists(name) .then(bool => console.log(bool)); } 

Thus, the function is executed and seems to work correctly when it prints to the console when there is a match. However, console.log () is not executed in the component. I think the “that” part is never achieved. In a separate note, is there a way to stop the forEach loop after a match is found?

Any help would be greatly appreciated, as I could not find the answers to all of this.

+7
typescript angularfire2
source share
1 answer

The problem is that the toPromise converts the observable into a promise that resolves the observable final value. This means that the observable must end before the promise is resolved.

In AngularFire2, control and object observable objects are not populated; they are repeated every time the database is changed.

You can solve the problem by 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(); 
+13
source share

All Articles