使用AngularJs NgResource从localhost加载JSON文件

use AngularJs NgResource to load JSON file from localhost

本文关键字:加载 JSON 文件 localhost AngularJs NgResource 使用      更新时间:2023-09-26

概述

我正在构建一个应用程序(运行在MAMP上),它保存联系人信息,并将扩展以保存更多数据,如项目名称和;截止日期,一旦该部分功能正常。

问题

当用户访问/projects.php#/project/时,我希望他们看到所有项目名称的列表,并带有指向其详细信息页面的链接。

  1. 我应该如何编写以下内容来访问我的所有数据

我需要末尾的.json吗?

@id是做什么的?

return $resource('data/project.json/:id', {id: '@id'});

当用户访问/projects.php#/project/a-gran-goodn时,我希望他们能看到这个项目的详细信息(目前,只有名称和地址)。

  1. 我应该如何写以下内容来按Id返回我的数据?$scope.project = $routeParams.id ? Project.get({id: $routeParams.id}): new Project();

plunkr文件

http://plnkr.co/edit/7YPBog

project.json

此文件位于http://localhost:8888/angularjs/ProjectsManager/data/project.json

[
{ "address" : [ " 3156 Dusty Highway",
        " Teaneck New Jersey 07009-6370 US"
],
        "id" : "a-gran-goodn",
        "name" : "Grania Goodner",
        "phone" : " (862) 531-9163"
},
{ "address" : [ " 62 Red Fawn Moor",
        " Rodney Village West Virginia 25911-8091 US"
],
        "id" : "b-aime-defranc",
        "name" : "Aimery Defranco",
        "phone" : " (681) 324-9946"
}
]

app.js

var projectsApp = angular.module('projects', ['ngResource']);
projectsApp.config(function($routeProvider) {
  $routeProvider
          .when('/', {
    controller: 'ProjectListCtrl',
    templateUrl: 'partials/projectlist.html'})
          .when('project/:id', {
    controller: 'ProjectDetailCtrl',
    templateUrl: 'partials/projectdetail.html'
  })
          .otherwise('/');
});
projectsApp.factory('Project', function($resource) {
  return $resource('data/project.json/:id', {id: '@id'});
});
projectsApp.controller('ProjectListCtrl', function(Project, $scope) {
  $scope.projects = Project.query();
  console.log($scope.projects);
});
projectsApp.controller('ProjectDetailCtrl', function(Project, $routeParams, $scope) {
  $scope.project = $routeParams.id
          ? Project.get({id: $routeParams.id})
          : new Project();
});

partials/projectlist.html

<a href="#/project/" class="btn">Add new item</a>
<ul class="unstyled">
    <li ng-repeat="project in projects">
    <div class="well">    
      <h2><small>{{project.id}}</small> {{project.name}}</h2>
      <a href="#/project/{{project.id}}" class="btn btn-link">View Info for {{project.name}}</a>
        </div>
  </li>
</ul>

partials/projectdetails.html

<h3>Information</h3>
<p>Name: {{project.name}}</p>
<p>Phone Number: {{project.phone}}</p>
<p ng-repeat="line in project.address">{{line}}</p>

index.php

<?php
header('Access-Control-Allow-Origin: *');
?>
<!doctype html>
<html ng-app="projects">
  <head>
    <meta charset="utf-8">
    <title ng-bind="title" ng-cloak>Restaurant &mdash;</title>
    <link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
  </head>
  <body ng-controller="ProjectListCtrl">
    <a class="brand" href="#">Projects Manager</a>
    <div id="app-container" class="container-fluid">
      <div class="row-fluid">
        <div class="span12" id="main" ng-view>
        </div><!--/.span12-->
      </div><!--/.row-fluid-->
      <footer>Copyright Projects &copy; 2013</footer>
    </div><!--/.container-->

    <script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
    <script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
    <!-- Don't forget to load angularjs AND angular-resource.js --> 
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.js></script>
    <!--Controllers-->
    <script src="app.js"></script>
  </body>
</html>

由于您不能像使用RESTful风格的URL那样对原始JSON文件进行查询(这就是$resource的构建目的),因此您可以获取JSON的副本,然后构建自己的queryget等,以查看数据并返回正确的内容。这有点棘手,因为您还想支持new Project,这在使用文件备份存储时没有什么意义,但本例支持它:

projectsApp.factory('Project', function($http) {
  // Create an internal promise that resolves to the data inside project.json;
  // we'll use this promise in our own API to get the data we need.
  var json = $http.get('project.json').then(function(response) {
    return response.data;
  });
  // A basic JavaScript constructor to create new projects;
  // passed in data gets copied directly to the object.
  // (This is not the best design, but works for this demo.)
  var Project = function(data) {
    if (data) angular.copy(data, this);
  };
  // The query function returns an promise that resolves to
  // an array of Projects, one for each in the JSON.
  Project.query = function() {
    return json.then(function(data) {
      return data.map(function(project) {
        return new Project(project);
      });
    })
  };
  // The get function returns a promise that resolves to a
  // specific project, found by ID. We find it by looping
  // over all of them and checking to see if the IDs match.
  Project.get = function(id) {
    return json.then(function(data) {
      var result = null;
      angular.forEach(data, function(project) {
        if (project.id == id) result = new Project(project);
      });
      return result;
    })
  };
  // Finally, the factory itself returns the entire
  // Project constructor (which has `query` and `get` attached).
  return Project;
});

您可以像使用任何其他承诺一样使用queryget的结果:

projectsApp.controller('ProjectListCtrl', function(Project, $scope) {
  $scope.projects = Project.query();
});
projectsApp.controller('ProjectDetailCtrl', function(Project, $routeParams, $scope) {
  $scope.project = $routeParams.id
          ? Project.get($routeParams.id)
          : new Project();
});

注意Project.get($routeParams.id)的更改;此外,更新后的Plunker还修复了$routeProvider配置中的一个问题。

这一切都在这里得到了证明:http://plnkr.co/edit/mzQhGg?p=preview

我会在这里粘贴一个通用代码,我用它从本地或远程服务器获取json,也许它会帮助你:

它使用一个工厂,你可以在需要的时候打电话给它。

app.factory('jsonFactory', function($http) {  
  var jsonFactory= {      
    fromServer: function() {        
        var url = 'http://example.com/json.json';
            var promise = $http.jsonp(url).then(function (response) {
          return response.data;
        });      
      return promise;
    },
    hospitals: function() {     
        var url = 'jsons/hospitals.js';               
            var promise = $http.get(url).then(function (response) {
          return response.data;
        });      
      return promise;
    }        
    };
  return jsonFactory;
});

然后当你需要调用它时:

function cardinalCtrl(jsonFactory, $scope, $filter, $routeParams) {
   jsonFactory.hospitals().then(function(d){
        $scope.hospitals=d.hospitals;
   });
   jsonFactory.fromServer().then(function(d){
        $scope.fromServer=d.hospitals;
   });
}