【问题标题】:How to map Object from http.get to Array?如何将对象从 http.get 映射到数组?
【发布时间】:2023-04-01 11:31:01
【问题描述】:

我有一个从本地文件中获取 JSON 数据的服务。我想将http.get 返回的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 类型,但我想更明确地处理数据。

【问题讨论】:

标签: json typescript kendo-ui get angular8


【解决方案1】:

httpClient.get() 方法的重载之一允许指定它返回的类型:

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

【讨论】:

猜你喜欢
  • 2015-06-25
  • 1970-01-01
  • 1970-01-01
  • 2022-11-24
  • 1970-01-01
  • 2021-04-18
  • 1970-01-01
  • 1970-01-01
  • 2020-11-09
相关资源
最近更新 更多