如何将JSON文件从后端传递到前端

时间:2018-12-27 14:38:11

标签: json angular spring

我有一个JSON文件,其中包含后端(Spring)中的产品列表。我希望能够将内容传递到前端(在Angular中)。

我在前端用angular制作的资产文件夹中有一个JSON文件。 这是JSON文件:

    [ {
        "brand": "",
        "category": {
          "id": 29,
          "name": "hand held"
        },
        "description": "New D131 Scanner complete",
        "hidden": false,
        "id": 10,
        "image": null,
        "productNumber": "E14NO1617",
        "quantity":1
      },
      {
        "brand": "",
        "category": {
          "id": 29,
          "name": "hand held"
        },
        "description": "New D132 Scanner complete",
        "hidden": false,
        "id": 10,
        "image": null,
        "productNumber": "E14NO1617",
        "quantity":1
      },
      {
        "brand": "",
        "category": {
          "id": 50,
          "name": "card reader"
        },
        "description": "USB,
        "hidden": false,
        "id": 26,
        "image": null,
        "productNumber": "ST-1044UB",
        "quantity": 1
      }
      ]

然后我在服务中具有以下功能的表上显示对象(本例中的产品):

    getTemplates() : Promise<Product[]> {
      return this.http.get<Product[]>("http://localhost:4200/assets/BirdyProducts.json")
        .toPromise();
    }

这就像我希望它被显示一样, 但是我不想将JSON存储在前端资产文件夹中。 我希望它位于资源文件夹的后端,并使用rest-controller发送该文件,但仍然得到相同的结果。

我在Objectmapper,JSONObjects等方面做了很多尝试,但是没有找到解决方案。

2 个答案:

答案 0 :(得分:1)

@Controller
public class BirdyProductsController {

    @RequestMapping(
      value = "/birdyProducts", 
      method = RequestMethod.GET, 
      produces = MediaType.APPLICATION_JSON_VALUE
    )

    String getBirdyProducts() {
        return "json/BirdyProducts.json";
    }
}

这对我有用。

JSON文件的路径:\ src \ main \ resources \ static \ json \ BirdyProducts.json

答案 1 :(得分:0)

@RestController
@RequestMapping
public class ExampleController {
    @GetMapping("/BirdyProducts")
    public InputStreamResource getJsonFile() throws IOException {
        return new InputStreamResource(new ClassPathResource("/assets/BirdyProducts.json").getInputStream());
    }
}

当我请求http://localhost:8080/BirdyProducts时,我得到文件的内容。

该文件位于后端的\src\main\resources\assets文件夹中。

相关问题