0

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.

3
  • 2
    keep it in assets & Then use this.http.get('assets/file.json'); Commented May 3, 2017 at 7:27
  • @ParthGhiya Thank you so much,I followed the instruction and it works +1 Commented May 3, 2017 at 7:28
  • i updated as answer :) you can accept & +1 . Also Angular JS Is angular 1 And angular 2/4 onwards is angular. Use naming accordingly. Commented May 3, 2017 at 7:30

1 Answer 1

2

Keep it in assets Folder & Use

this.http.get('assets/file.json')
Sign up to request clarification or add additional context in comments.

Comments

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.