2
votes

I have one json file named fake.json inside assets in my angular application. Path of this file is like this.

MyApp => src => assets => json => fake.json

I want to make a POST request to this file using HttpClient in my component which is in inside app folder.

MyApp => src => app => Statistics => statistics.component.ts

Component source code

export class StatisticsComponent {

  persons: Person[];

  options = {
    sDom: 'rt<"bottom"p>',
    pagingType: 'full_numbers',
    pageLength: 10,
    serverSide: true,
    processing: true,
    ajax: (dataTablesParameters: any, callback) => {
      this.http
        .post<DataTablesResponse>(
          './../../assets/json/fake.json',
          dataTablesParameters, {}
        ).subscribe(resp => {
          this.persons = resp.data;
          callback({
            recordsTotal: resp.recordsTotal,
            recordsFiltered: resp.recordsFiltered,
            data: []
          });
        });
    },
    columns: [
      { data: "id" },
      { data: "firstName" },
      { data: "lastName" }
    ]
  };

  constructor(private http: HttpClient) {

  }

}

class Person {
  id: number;
  firstName: string;
  lastName: string;
}

class DataTablesResponse {
  data: any[];
  draw: number;
  recordsFiltered: number;
  recordsTotal: number;
}

I occurred this following error

HttpErrorResponse Http failure response for http://localhost:4200/assets/json/fake.json: 404 Not Found

I got 2 doubts over this.

  1. Is it valid to make a POST request to a local json file using Http or HttpClient. (Till now I have done GET request using Http not HttpClient and got the data successfully)

  2. Why it returns 404 Not Found when the file is present there inside the folder.

Need Help.

2
Which version of angular-cli do you use? - Bunyamin Coskuner
@BunyaminCoskuner Angular CLI version 1.6.1 - Rishikesh Dehariya

2 Answers

4
votes

It's because whatever you put inside assets folder will be served via GET requests. You can test this by simply navigation to http://localhost:4200/assets/json/fake.json on browser. If you want to test POST method, you need to start a server.

HttpModule is deprecated and removed in later versions of Angular. You should change it to HttpClientModule

To test it with HttpClient, you can do the following.

Add HttpClientModule to your AppModule

Inject HttpClient within your component

constructor(private httpClient: HttpClient) {}

And make the request as follows

this.httpClient.get('/assets/json/fake.json',  { observe: 'body' })
    .subscribe(result => {
      console.log(result);
    });
1
votes

In order to read or write data from a local JSON file, you can use json-server.

  1. Create fake.json file.
  2. Install json-server npm i json-server.
  3. Start the JSON Server json-server --watch fake.json.
  4. Now request the server on http://localhost:3000/

Follow the documentation link: https://www.npmjs.com/package/json-server