有没有更好的方法来获取 Angular 上的 API?

Is there a better way to fetch an API on Angular?

昨天我正在做一个项目,因为我正在自学Angular。我试图对 PokeAPI 进行 API 调用,因为我想获取 Pokemon 及其名称的 .svg。我成功了,但我真的不知道这是否可以改进并做得更好。

我提供了所有代码(因为它是一个非常小的程序)和一个用于测试目的的 Stackblitz 示例。

pokemon.service.ts

import { Injectable } from '@angular/core';

import { HttpClient } from '@angular/common/http';

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

  constructor(private http: HttpClient) { }

  getRandomPokemon(id: number) {
    return this.http.get(`https://pokeapi.co/api/v2/pokemon/${id}`);
  }
}

app.component.html

<img src="{{ image }}" width="300" height="300">
<h2>
  {{ actualPokemon }}
</h2>

app.component.ts

import { Component } from '@angular/core';
import { PokemonService } from './services/pokemon.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'RandomPokemon';
  actualPokemon = '';
  image = '';

  constructor(private pokemonService: PokemonService) { }

  ngOnInit(): void {
    this.getRandomPokemon();
    // console.log(this.actualPokemon);
  }
  
  getRandomPokemon() {
    this.pokemonService.getRandomPokemon(Math.floor(Math.random() * 807) + 1).subscribe(
      (data: any) => {
        this.actualPokemon = data.name;
        this.image = data.sprites.other.dream_world.front_default;
        console.log(this.actualPokemon);
      },
      error => {
        console.log(error);
      }
    );
  }
}

我已经在 app.module.ts 中导入了 HttpClientModule 但我不会将其粘贴到此处,因为它只是一个依赖关系。

嗯,这是一个非常普通的 http 请求,如果从您这边发出任何错误,您甚至不会理解它失败的原因。我不建议向后端发出这种请求。您想尽可能控制数据

  • 未指定 response type
  • 未指定 observe: response
  • 无响应序列化程序
  • 没有响应数据的接口
  • 没有错误处理

什么都没有,就是一个普通的请求。

有点像样的请求看起来像

getRandomPokemon(id: number): Observable<Pokemon> {
   const headers = new HttpHeaders().set('content-type', 'application/json');

   return this.http.get<Pokemon>(`https://pokeapi.co/api/v2/pokemon/${id}`, { headers: headers, observe: "response" })
   .pipe(
    catchError((err) => {
      // throw error to observer and treat it in subscription
      return throwError(() => new Error(err));
    })
  );
}