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.
typescript angularfire2
Leonidas
source share