如何将对象从 http.get 映射到数组?

How to map Object from http.get to Array?

我有一项服务可以从本地文件中获取 JSON 数据。我想将 http.get returns 的 Object 类型转换为这个数组:Array<{ bookName: string, bookId: number }>。你可以在这个 Github repository.

中看到我所有的源代码

bible.service.ts

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

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

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

  constructor(private http: HttpClient) { }

  public fetch(file: string) {
    return this.http.get(file);
  }
}

bible.component.ts(简体)

import { Component, OnInit } from '@angular/core';

import { BibleService } from "../bible.service";

@Component({
  selector: 'app-bible',
  templateUrl: './bible.component.html',
  styleUrls: ['./bible.component.scss']
})
export class BibleComponent implements OnInit {
  dataBooks: Array<{ bookName: string, bookId: number }>;

  constructor(
    private bibleService: BibleService,
  ) {
    // fetch JSON data asynchronously 
    this.bibleService.fetch('./assets/bible/books.json')
      .subscribe(response => {
        this.dataBooks = response;  // how do I map this?
      }, error => {
        console.error(error);
      }, () => {
      });
  }

  ngOnInit() {
  }
}

代码当前使用类型 any,但我想更明确地处理数据。

httpClient.get() 方法的重载之一允许指定它 returns:

的类型
import { Injectable } from '@angular/core';

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

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

  constructor(private http: HttpClient) { }

  public fetch(file: string) {
    return this.http.get<Array<{ bookName: string, bookId: number }>>(file); // <---------------
  }
}