Reputation: 3541
I am trying to get a json array through a data.json file, but angular js does not find data.json (returning 404 Error
). I have tried many ways but still unable resolve this issue (I just started to learn angular 2). Following is my related files and code:
app/user/user.service.ts // User Service File
import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class UserService{
private JsonDirectory: string = "app/data.json"
constructor(private _httpReference: Http){}
getUsers(){
return this._httpReference.get(this.JsonDirectory)
.map((responseReference:Response) => responseReference.json());
}
}
In the same location I have another file named user.component.ts
import { Component, OnInit } from '@angular/core';
import {UserService} from './user.service';
export class UserComponent implements OnInit{
UserArray = [];
ngOnInit(){
this.userService.getUsers()
.subscribe(resUserData => this.UserArray = resUserData);
}
}
Data.json File Code
[
{"id":1,"name":"Ayaz","gender":"Male"},
{"id":2,"name":"Ali","gender":"Male"},
{"id":3,"name":"Shah","gender":"Male"},
{"id":4,"name":"Khan","gender":"Male"}
]
I put the data.json
file in different location like app/data.json, user/data.json and on root and then I changed the url according to the location, but it does not find it and returns 404 Error
.
Upvotes: 0
Views: 162
Reputation: 6949
Keep it in assets Folder & Use
this.http.get('assets/file.json')
Upvotes: 2