POST request to a local json file using HttpClient

后端 未结 2 865
清歌不尽
清歌不尽 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: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);
        });
    

提交回复
热议问题