我有一个从本地文件中获取JSON数据的服务。我想将Object
返回的http.get
类型转换为以下数组: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);
}
}
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
,但我想更明确地说明数据。
答案 0 :(得分: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); // <---------------
}
}