0

I have a service that fetches JSON data from local files. I would like to convert the Object type that http.get returns to this array: Array<{ bookName: string, bookId: number }>. You can see all of my source code in this 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 (simplified)

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() {
  }
}

The code is currently working with type any, but I would like to be more explicit with the data.

1

1 Answer 1

1

One of the overloads for the httpClient.get() method allows to specify the type that it 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); // <---------------
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

OK. Thank you sir. I suppose I need a separate service method for each return then: books, chapters, and verses.
It looks like Overload #15 here: angular.io/api/common/http/HttpClient#get

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.