juanjinario
juanjinario

Reputation: 745

How to use async/await with the pipe map of an observable?

I make a post to the database, I must make a map to treat the response of that query, if in the response one of the data that I need does not come, I must make another query, I do this query with an await / async but it does not seem to work when I debug. The code as the following:

// Service (I have changed the endpoints)
public login(username: string, password: string) {
    let loginDto = { info: new LoginDto(username, password) };
    return this.http.post('https://jsonplaceholder.typicode.com/posts', { title: 'Angular POST Request Example' }).pipe(
      map(response => {
        return this.processLoginResponse(response);
      })
    );
}

private async processLoginResponse(response) {
    let permissions = await this.getPermissionsFromAPI(116677);
    this._user = {username: 'Jhon', permissions: permissions};
    return this._user
  }

private getPermissionsFromAPI(userId): Promise<any> {
    return this.http.get('https://jsonplaceholder.typicode.com/todos/1').toPromise();
  }

// Component
onSubmit(e) {
    const { username, password } = this.formData;
    this.authService
      .login(username, password)
      .subscribe(
        data => {
          data.then(x => console.log(x));
          // things
        }
      );
  }

Upvotes: 4

Views: 3701

Answers (1)

Arun s
Arun s

Reputation: 945

Try this solution. Instead of returning promises, i have used observables which is better . You could call subsequent requests using rxjs operators like below. We could get the desired result without usage of async/wait in this case :

import { HttpClient } from '@angular/common/http';
import { switchMap } from 'rxjs/operators';
import { Observable } from 'rxjs';

export class testService {
  constructor(private http: HttpClient) {}

     public login(username: string, password: string) {
           let loginDto = { info: new LoginDto(username, password) };
           return this.http.post('https://jsonplaceholder.typicode.com/posts', { title: 'Angular POST Request Example' }).pipe(
                switchMap((response) => {
                    return this.getPermissionsFromAPI(response);
                })
              );
        }
        
    getPermissionsFromAPI(userId): Observable<any> {
          return this.http.get('https://jsonplaceholder.typicode.com/todos/1'); 
     }

}


    onSubmit(e) {
        const { username, password } = this.formData;
        this.authService
          .login(username, password)
          .subscribe(
            data => {
              data.then(x => console.log(x));
              // things
            }
          );
      }

Upvotes: 3

Related Questions