Return Observable within Async Function


March 2019


19 time


I'm having trouble with the data I get from the server. I need to check if a username is available and then execute an http.get which is no problem, thing is I need to return the content of the http.get as an observable to create an object later.

registerUser(user: RegisterComponent): Observable<any> {

  let headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');

  let exists = this.http.get(this.url + "verifyCuentaUsuarioApp.php?cuenta=" + user.cuentaUser + "&id=" + user.passUser);

  exists.subscribe(response => {
    if (response != null) {
      //console.log("this is the message "+response.mensaje);
      if ([0].estatus == "0") {
        //I need the content of this request to be returned 
        this.http.get(this.url + 'registroClienteApp.php?' + params, { headers: headers });
      } else
        console.log("no disponible");

  return this.http.get(this.url + 'registroClienteApp.php?' + params, { headers: headers });

2 answers


Basically you need to flatten your observable returned by first http call and then switch to next http call depending on some logic (filter can help you with this). One of the operators that can help you is switchMap which is considered as a safer default to mergeMap and maintain only one inner subscription (like it is in your case). I created a StackBlitz demo for you.


Need to return an Observable? Start not with not subscribing but piping the Observable and use any of the flattening rxjs operators, for example:

this.http.get(// first request here).pipe(
    mergeMap((dataFromFirstRequest) => {
        if (dataFromFirstRequest suits requirement for second request) {
            return this.http.get(// second http request)
        } else {
            return of(false);   // return a falsy data indicating second request wasn't needed