如何在observable的管道映射中使用async/await?

3

我向数据库发布一篇文章,我必须制作一个映射来处理该查询的响应。如果在响应中没有我需要的数据之一,则必须进行另一个查询。我使用await/async进行此查询,但在调试时似乎无法正常工作。

代码如下:

// 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,这样可以在收到第一个HTTP请求(https://jsonplaceholder.typicode.com/posts)后再发起一个HTTP调用(getPermissionsFromAPI)。 - Random
你能给我一个带有我的测试端点的示例代码吗?从第一个请求中,我得到一个变量,然后将其发送到第二个查询中,它们不是独立的两个查询。 - juanjinario
1
你可以在这里看一下:https://blog.angular-university.io/rxjs-switchmap-operator/ - Random
1个回答

2
尝试这个解决方案。我使用了更好的可观察对象来替代返回承诺。您可以像下面这样使用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
            }
          );
      }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接