How to read Local JSON file in ionic V4?

this.http.get(‘assets/data/subtitles.json’).map(res => res.json()).subscribe(data => {
this.subtitles = data;
});

ionic V3 type not supported to ionic V4

It depends on the size. If the file is small, you could use JSON.parse. If the file is large, you’re better off using an asychronous parser. The NodeJS JSON type doesn’t have a parse function. But assuming your file is small, you can leverage Node and the standard JSON type like this:

fileToJSON(fileName: string): Promise<JSON> {
  return promisify(readFile)(fileName)
               .then(buffer => JSON.parse(buffer.toString()))
}
1 Like

Thanks for your response. in my case, "Property ‘map’ does not exist on type ‘Observable’ "

Why are you using an Observable instead of a Promise? Do you need to read from the file more than once?

yeah. Im using local JSON files now.

I found answer for this,

Angular apps rely on rxjs@5.5+ import map operator like this:
import { map } from "rxjs/operators";

And if you're using rxjs@6+ then execute the command for backward compatibility:
npm install --save rxjs-compat@6

Note Sometimes map operator gives an error Property map does not exist on type Observable<Object>

To kick this out, import Observable like this:
import { Observable } from "rxjs/Rx";

and user this code for read json file,

constructor(public http: Http) { }

  contactPersonData;

  ngOnInit() {

    if (this.contactPersonData) {
      return Promise.resolve(this.contactPersonData);
    }
    return new Promise(resolve => {
      this.http.get("./../assets/data/resource.json").
        pipe(map(
          (response) => response.json()
        )).
        subscribe(
          (data) => {
            {
              this.contactPersonData = data.results;
              resolve(this.contactPersonData);
            }
          }
        )

    });
  }

after that import provider you page and,

loadConectedPeople() {
    this.peopleSearch.ngOnInit()
      .then(contactPersonData => {
        this.contactedPeople = contactPersonData;
      });
  }
1 Like

Your code commits the explicit Promise antipattern.

1 Like