2017-01-16 48 views
0

我試圖在本地服務器上獲取json文件,其中存儲了少量數組。我試圖通過使用運行代碼,如下$ http服務來實現這一目標:將json文件轉換爲angularjs

(function(){ 
    var app = angular.module('store', ['store-products']); 
    app.controller('StoreController',['$http', function($http){ 
     var store = this; 
     store.products = []; 
     $http.get('products.json').success(function(data){ 
      store.products = data; 
     }) 
})(); 

而且我products.json文件:

[ { 
    "name" : "Lasagna", 
    "price" : 250, 
    "images":[{"full":"images/lasagne.jpg"}], 
    "Description":"Lasagne are wide, flat-shaped pasta, and possibly one of the oldest types of pasta.The word 'lasagne', and, in many non-Italian languages, the singular 'lasagna', can also refer to a dish made with several layers of lasagne sheets alternated with sauces and various other ingredients.", 
    "canPurchase": true, 
    "Reviews":[] 

      }, 
      { 
    "name":"Shawarma", 
    "price":300, 
    "images":[{"full":"images/shawarma.jpg"}], 
    "Description":"Shawarma or Shawurma is a Levantine meat preparation, where lamb, chicken, turkey, beef, veal, buffalo meat, or mixed meats are placed on a spit (commonly a vertical spit in restaurants), and may be grilled for as long as a day.Shavings are cut off the block of meat for serving, and the remainder of the block of meat is kept heated on the rotating spit. Shawarma can be served on a plate (generally with accompaniments), or as a sandwich or wrap. Shawarma is usually eaten with tabbouleh, fattoush, taboon bread, tomato, and cucumber. Toppings include tahini, hummus, pickled turnips, and amba", 
    "canPurchase": true, 
    "Reviews":[] 
    }] 

而且我的html代碼:

<!doctype html> 
<html ng-app="store"> 
<head> 
    <link rel="stylesheet" href="styles/bootstrap.min.css"> 
</head> 
<body ng-controller="StoreController as store"> 
    <h1 align="center"><ul>Food Junkie</ul></h1> 
    <h2 align="center">-It's all gonna be alright-</h2> 
    <ul class="list-group"> 
     <li class="list-group-item" ng-repeat ="product in store.products"> 
      <product-title></product-title> 
      <product-images></product-images> 
      <button ng-show="product.canPurchase"><img src="images/cart_64x64.jpg"/></button></br> 
      <product-panel></product-panel> 
     </li> 
    </ul> 

    <script type="text/javascript" src="scripts/angular.min.js"></script> 
    <script type="text/javascript" src="scripts/ang.js"></script> 
</body> 
</html> 
+0

當您從Web瀏覽器或其他客戶端直接請求'/product.json'時,您會得到什麼結果? – lealceldeiro

+0

@AsielLealCeldeiro:我收到了我列出的數組。 –

回答

0

你可以像這樣訪問它,但你的網址是錯誤的。如果JSON文件是在根只是用$http.get('product.json'),否則不要用破折號/開始,如:$http.get('path/to/product.json')

要知道你的角版本太多,因爲最新的版本將取代$http.success().error().then().catch()

+0

是的,我試圖刪除反斜槓,但沒有什麼改變,我正在使用的angularjs的縮小版本存儲在我的本地服務器(不是CDN),我敢肯定它不是更新後的版本。 –

+0

你有什麼錯誤? 404?如果你服務的是json,你是否嘗試過使用絕對路徑而不是相對路徑? – Hiraqui

+0

是的,當我將路徑提供給.json文件時,我收到了列出的數組,但是我在我的js文件中提到的路徑只是文件名,導致它位於根文件夾中。 –