【问题标题】:NestJS use the content of a API call on another API call and return the content of the last API callNestJS 在另一个 API 调用上使用一个 API 调用的内容,并返回最后一个 API 调用的内容
【发布时间】:2022-08-13 09:49:22
【问题描述】:

我试图在另一个 API 请求中使用第一个 API 请求中的内容,但没有成功。只有在第一个请求完成后,我才需要执行第二个请求。

现在这是我到目前为止得到的:

@Injectable()
export class WeatherService {
  constructor(private httpService: HttpService) {}
  getWeather(city: GetWeatherDto): Observable<AxiosResponse<any>> {
    return this.httpService.post(`http://localhost:3000/cities`, city).pipe(
      map((response) => response.data),
      tap((data) =>
        this.httpService
          .get(
            `https://api.openweathermap.org/data/2.5/weather?id=${data.city_id}&appid=APIKEY&lang=pt_br`,
          )
          .pipe(map((response) => response.data)),
      ),
    );
  }
}

    标签: typescript axios rxjs nestjs


    【解决方案1】:

    我认为您可以使用 switchMap 运算符来达到预期的结果。您可能会进行一些小的更改以使其适合您的需求。

    @Injectable()
    export class WeatherService {
      constructor(private httpService: HttpService) {}
      getWeather(city: GetWeatherDto): Observable<AxiosResponse<any>> {
        return this.httpService.post(`http://localhost:3000/cities`, city).pipe(
          switchMap((response) =>
          this.getCityWheaterById(response.data.city_id)),
          
        );
      }
    
     private getCityWheatherById(id: string) {
       this.httpService
              .get(
                `https://api.openweathermap.org/data/2.5/weather?
                 id=${id}&appid=APIKEY&lang=pt_br`,
              ).pipe(map((response) => response.data)),
      }
    }
    
    
    
    

    【讨论】:

      【解决方案2】:

      您可以使用状态码来确定请求是否成功,甚至在需要时确定它是否有数据。

      tap((response) =>
       if (response.status == 200){
         if (response.data){
           this.httpService.get(`https://api.openweathermap.org/data/2.5/weather?id=${data.city_id}&appid=APIKEY&lang=pt_br`,).pipe(map((response) => response.data)),),
          }
       }
      ),
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-10
        • 1970-01-01
        • 2019-02-18
        • 2020-09-10
        相关资源
        最近更新 更多