簡體   English   中英

如何將JSON文件從后端傳遞到前端

[英]How to pass a JSON file from the back-end to the front-end

我有一個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等做了很多嘗試,但是沒有找到解決方案。

@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

@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文件夾中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM