【问题标题】:How to pass a JSON file from the back-end to the front-end如何将 JSON 文件从后端传递到前端
【发布时间】:2019-05-25 14:00:07
【问题描述】:

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

我在前端的资产文件夹中有一个 JSON 文件,它是用 Angular 制作的。 这是 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 存储在我的前端资产文件夹中。 我希望它在我的后端资源文件夹中,并使用休息控制器发送文件,仍然得到相同的结果。

我对 Objectmapper、JSONObjects 进行了很多尝试,但没有找到解决方案。

【问题讨论】:

  • 您可以存储 JSON 并创建 API 以返回数据

标签: json angular spring


【解决方案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

【讨论】:

    【解决方案2】:
    @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 文件夹中。

    【讨论】:

      猜你喜欢
      • 2020-01-17
      • 2012-11-12
      • 1970-01-01
      • 2021-12-23
      • 2020-03-01
      • 2016-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多