POST request to a local json file using HttpClient

后端 未结 2 864
清歌不尽
清歌不尽 2020-12-21 23:49

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

MyApp => s

相关标签:
2条回答
  • 2020-12-22 00:23

    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

    0 讨论(0)
  • 2020-12-22 00:48

    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);
        });
    
    0 讨论(0)
提交回复
热议问题