簡體   English   中英

使用 http 調用解決可觀察屬性

[英]Resolve observable properties with http calls

Im trying to write an API interface for the public https://pokeapi.co/ When trying to query for a Pokémon, the API doesn't return the entire model, it returns url references to children instead.

(試圖查詢https://pokeapi.co/api/v2/pokemon/name

而不是預期的

Pokemon { 
  id,
  name,
  types[ (Actual model)
    {
      id,
      name,
      otherProperties...
    }
  ]
} 

我明白了

Pokemon { 
  id,
  name,
  types[ (Reference to the actual model)
    {
      name,
      url
    }
  ]
} 

How do i make a method findPokemonByName(string: name) which returns the root pokemon and maps the types as nested http requests to https://pokeapi.co/api/v2/type/name using HttpClient and rxjs?

這是服務的預覽:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { tap, switchMap } from 'rxjs/operators';
import { forkJoin } from 'rxjs';

@Injectable()
export class PokemonService {
  private baseAPIUrl = 'https://pokeapi.co/api/v2/';
  constructor(private httpClient: HttpClient) {

   }

   public getPokemonByName(name: string) {
     return this.httpClient.get(`${this.baseAPIUrl}pokemon/${name}`)
     .pipe(
       switchMap((pokemon: any) => {
         return forkJoin({
           types: forkJoin(this.generateRequestsForTypes(pokemon.types))
         })
       }, (pokemon, result) => {
         pokemon.types = result.types;
         return pokemon;
       }),
     )
   }

  private getPokemonTypeByUrl(url: string) {
    return this.httpClient.get(url);
  }

  private generateRequestsForTypes(types: any[]) {
    return types.map((type) => this.getPokemonTypeByUrl(type.type.url))
  }
}

當然,您必須添加類型,但我認為這可能是一個好的開始。

請注意請求的數量,因為每個嵌套屬性都可以是一個請求。

使用結果選擇器 function(上例中 switchMap 運算符的最后一個參數)。

堆棧閃電戰

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM