【问题标题】:How to use async/await with the pipe map of an observable?如何将 async/await 与 observable 的管道图一起使用?
【发布时间】:2021-05-24 14:52:40
【问题描述】:

我向数据库发帖,我必须制作一个地图来处理该查询的响应,如果在响应中我需要的数据之一没有出现,我必须进行另一个查询,我用这个查询一个等待/异步,但在我调试时它似乎不起作用。 代码如下:

// 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
        }
      );
  }

【问题讨论】:

  • 不使用 async/await 怎么办?您正在寻找的是switchMap 而不是map 我猜,以便在收到第一个(https://jsonplaceholder.typicode.com/posts)后进行HTTP调用(getPermissionsFromAPI
  • 你能给我一个包含我的测试端点的示例代码示例吗?从一开始,我得到一个在第二个查询中发送的变量,它们不是 2 个独立的查询

标签: angular typescript async-await rxjs


【解决方案1】:

试试这个解决方案。我没有返回承诺,而是使用了更好的 observables。您可以使用如下所示的 rxjs 运算符调用后续请求。在这种情况下,我们可以在不使用 async/wait 的情况下获得所需的结果:

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
            }
          );
      }

【讨论】:

    猜你喜欢
    • 2014-03-13
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    • 2019-04-15
    • 2014-06-19
    • 2018-01-14
    • 2018-09-12
    相关资源
    最近更新 更多