简体   繁体   中英

Angular2 return true/false with subscription

I need to check if user exists in the database and return true if so. I have a function (i am using firebase by the way):

  checkIfUserExists(login: string): boolean {
    this.af.database.list('/users', {
      query: {
        orderByChild: 'login',
        equalTo: login
      }
    }).subscribe(response => {
      if(response.length === 0 ) return true
    })
    return false
  }

The problem is that the function always returns false. It does not wait for checking subscription. Is there some way to fix it?

You could return the observable itself:

  checkIfUserExists(login: string): Observable<boolean> {
    return this.af.database.list('/users', {
      query: {
        orderByChild: 'login',
        equalTo: login
      }
    }).map(response => {
      if(response.length === 0 ) {
        return true;
      } else {
        return false;
      }
    });        
  }

In this case, you can use it like this:

checkIfUserExists('some username')
     .subscribe(userExists => {
       // Do something
     });

This is because your processing is asynchronous so you need to handle processing with callbacks. This way you'll be sure to execute processing when asynchronous processing are executed.

You can use either observables (rxjs - like in my sample) or promises for such use cases.

You could return a promise instead and then call find() :

 checkIfUserExists(login: string): boolean {
    return this.af.database.list('/users', {
      query: {
        orderByChild: 'login',
        equalTo: login
      }
    }).subscribe(response => {
      if(response.length === 0 )
        return true;
       return false;
    }).toPromise().find();

  }

You can return a promise using Native Promise API:

checkIfUserExists(login: string): boolean {
  return new Promise(function(resolve, reject) {
    this.af.database.list('/users', {
      query: {
        orderByChild: 'login',
        equalTo: login
      }
    }).subscribe(response => {
      if(response.length === 0 ) {
        reject();
      } else {
        resolve()
      }
    })
  });
}

Then use it as,

checkIfUserExists('login').then(function(response) {
  // found
}, function() {
  // not found
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM