angular 带有 rxjs 的 HttpClient

angular HttpClient with rxjs

我正在尝试在 angular 7 中做一件简单的事情。我只需要调用 1st a getKey REST api,然后使用returned 密钥将其传递给第二个 REST api getData 以获取我的数据。最后,我希望我的服务是 return 一个 Observable,所以当它完成所有过程时,我得到 returned 数据。这是我的代码:

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

    });
  }
}

我知道我做错了,因为我 return 订阅而不是 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);
          })
        );
       }

关于服务部分:

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

  getData$(){

return this.http.get("http://myservice/getKey", httpOptions )

  }

稍后在您的组件端:

 constructor(private myService: MyTestServiceService ) { }

 myMethodToCallMyService() {

   this.myService.getData$().subscribe(data => console.log(data));
 }
  1. 不要subscribe在你的服务中类。
  2. 从任何服务中导出您的 headerOptions (您可以使用通用服务来获取它们),因为您将在每个服务中使用它们,然后它们不应该依赖于特定的。

可以使用switchMap实现多次httpClient调用和return数据为Observable需要熟悉pipemap rxjs 运算符

像这样尝试

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").pipe(
      switchMap(key=>{
         return this.http.get("http", headers: new HttpHeaders({
          'Key': key
        }));
      }));
  }
}

希望这有帮助 - 检查这个库 rxjs - 编码愉快 :)

如果您想先获取一个密钥,然后在第二次调用中使用它来获取数据,concatMap 是您的好伙伴,因为它依赖于先前的可观察对象在继续之前完成。 switchMap 如果您想丢弃以前的可观察流并在前一个流发出值后立即启动一个新的可观察流。

因此,将此应用于您的服务:

getData$(): Observable<whatever you return in api here>{
    return this.http.get('getKeyUrl').pipe(
      concatMap(key => {
        const headers = new HttpHeaders({'Key': key});
        return this.http.get('urlTwo', httpOptions)
      }) 
    )     
}