【发布时间】:2023-04-01 11:31:01
【问题描述】:
我有一个从本地文件中获取 JSON 数据的服务。我想将http.get 返回的Object 类型转换为这个数组:Array<{ bookName: string, bookId: number }>。你可以在这个Github repository看到我所有的源代码。
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);
}
}
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