Angular 5 Service to read local .json file

user8770372 picture user8770372 · Nov 9, 2017 · Viewed 162.6k times · Source

I am using Angular 5 and I've created a service using the angular-cli

What I want to do is to create a service that reads a local json file for Angular 5.

This is what I have ... I'm a bit stuck...

import { Injectable } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

@Injectable()
export class AppSettingsService {

  constructor(private http: HttpClientModule) {
    var obj;
    this.getJSON().subscribe(data => obj=data, error => console.log(error));
  }

  public getJSON(): Observable<any> {
    return this.http.get("./assets/mydata.json")
      .map((res:any) => res.json())
      .catch((error:any) => console.log(error));

  }

}

How can I get this finished?

Answer

Bougarfaoui El houcine picture Bougarfaoui El houcine · Nov 9, 2017

First You have to inject HttpClient and Not HttpClientModule, second thing you have to remove .map((res:any) => res.json()) you won't need it any more because the new HttpClient will give you the body of the response by default , finally make sure that you import HttpClientModule in your AppModule :

import { HttpClient } from '@angular/common/http'; 
import { Observable } from 'rxjs';

@Injectable()
export class AppSettingsService {

   constructor(private http: HttpClient) {
        this.getJSON().subscribe(data => {
            console.log(data);
        });
    }

    public getJSON(): Observable<any> {
        return this.http.get("./assets/mydata.json");
    }
}

to add this to your Component:

@Component({
    selector: 'mycmp',
    templateUrl: 'my.component.html',
    styleUrls: ['my.component.css']
})
export class MyComponent implements OnInit {
    constructor(
        private appSettingsService : AppSettingsService 
    ) { }

   ngOnInit(){
       this.appSettingsService.getJSON().subscribe(data => {
            console.log(data);
        });
   }
}