Idiot_cheg
Idiot_cheg

Reputation: 125

Angular 2 - how to consume data from local json?

Thanks for every one who jumping into this for helping me . NOW its working like charm

Thanks all

Could someone tell me how to use local JSON data?

I am not sure what am missing in configuration (problem might be in HTTP config). Below is my file structure.

├───app
    about.component.html
about.component.ts
app.component.css
app.component.html
app.component.spec.ts
app.component.ts
app.module.ts
app.routing.ts
dataservice.ts
home.component.html
home.component.ts
dummy.json
└───environments

myService.ts

@Injectable()
export class dataService implements OnInit {
  constructor(private Http: Http) {}
  private _url: string = "assets/js/dummy.json";
  ngOnInit() {}
  gethomedata() {
    return this.Http.get(this._url).map(response => response.json());
  }
}

homeComponent.ts

@Component({
  templateUrl: './home.component.html',
})
export class home implements OnInit {
  constructor(private http: Http, private dataService: dataService) {}
  home = [];
  ngOnInit() {
    this.dataService.gethomedata().subscribe(data => {
      console.log('home', data);
      this.home.push(data);
    })
  }
}

When I run, it shows 404 not found error. Can tell me where I did wrong?

enter image description here

enter image description here

Upvotes: 3

Views: 357

Answers (1)

Victor Noël
Victor Noël

Reputation: 862

Theoretically, you have two options:

  1. You serve the json as an asset and retrieve it via the HttpClient.
  2. You put the json in the source code, you import it in your typescript and when it is compiled, it is transformed into an object by webpack.

In practice, the second point is not doable as far as I know, because it involves the modification of the webpack configuration and it is not currently possible with Angular.

Upvotes: 2

Related Questions