带有 rxjs 的 Angular HttpClient

标签 angular rest rxjs angular-http angular-httpclient

我正在尝试在 Angular 7 中做一件简单的事情。我只需要调用第一个 getKey REST api,然后使用返回的 key 将其传递给第二个 REST api getData 获取我的数据。最后,我希望我的服务返回一个 Observable,这样当它完成所有过程时,我就可以获得返回的数据。这是我的代码:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class MyTestServiceService {

  constructor(private http: HttpClient) { }

  getData$(){

    return this.http.get("http://myservice/getKey").subscribe((key : string) => {

      const httpOptions = {
        headers: new HttpHeaders({
          'Key': key
        })
      };

      return this.http.get("http", httpOptions).subscribe(data => {
        return data;
      })

    });
  }
}

我知道我做错了,因为我返回的是订阅而不是 Observable。但就是不知道该怎么做。温柔点,我刚刚开始玩 RxJs,并且来自 AngularJs/promise 背景:)

谢谢

最佳答案

You can use switchMap to achieve this -

   getData$(){
        return this.http.get("http://myservice/getKey").pipe(
          switchMap(key=>{
              const httpOptions = {
            headers: new HttpHeaders({
              'Key': key
            })
          };
          return this.http.get("http", httpOptions);
          })
        );
       }

关于带有 rxjs 的 Angular HttpClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53265225/

相关文章:

angular - TypeScript 找不到模块错误

Angular 服务回调命令组合

javascript - Ajax 调用以消耗本地主机上的剩余服务

angular - 类型 'interval' 上不存在属性 'Observable<any>'

rxjs - 如何使用 RxJS Observables 制作倒数计时器?

angular - 升级到angular 12后,所有 Material 成分都是 "not a known element"

javascript - Angular 7 : Cannot find control with name: formControlName in angular reactive form

http - 了解 REST : is GET fundamentally incompatible with any "number of views" counter?

mysql - 如何处理 org.hibernate.exception.ConstraintViolationException,我使用 try catch 但它不起作用

javascript - 当没有编写 api 时,如何模拟 Angular2 中的 http observable