【问题标题】:Save API response to server as JSON file with AngularJS使用 AngularJS 将 API 响应保存为 JSON 文件到服务器
【发布时间】:2016-01-20 02:59:07
【问题描述】:

我正在尝试在 AngularJS 中创建一个聚合来自多个 API 的数据的应用程序。对于一些公共 API,存在请求限制,并且我想要提取的大部分数据不会非常频繁地更新,因此每月只需要针对特定​​ ID 的一次请求。为了解决这个问题,我设置了一个工厂,它首先检查服务器上的本地文件,如果不存在,它会转到 API 并执行 GET 请求。

从那里,一旦请求完成,我想将该文件保存到服务器,名称由响应中的字段设置。

我发现了一些将 PHP 与 AngularJS 结合使用的示例,但我不确定如何使用动态名称保存 JSON 文件……或者这是否是避免请求限制的最佳做法.

var apiUrl = 'https://example.com/api?userID=';

$http.get(apiUrl + $stateParams.userID).
 success(function(data) {
   $scope.content = data;
   $scope.userID = data.userID
    function(){
      $http.post('saveJson.php', $scope.content).then(function() {
      // log success
      });
    };
 }).
 error(function() {
   // log error
 });

PHP

<?php
$json = file_get_contents("php://input");
$file = fopen('/var/www/USERID.json','w+');
fwrite($file, $json);
fclose($file);
?>

【问题讨论】:

  • 您从 3rd 方 API 获得的响应有多大?如果字符数在数千或更少,您可以将 JSON 字符串存储在数据库中,而不是在服务器上创建单独的文件。
  • 在大多数情况下,每个 JSON 响应可能在 500-3000 个字符之间。您是想将整个 JSON 响应存储在数据库的一列中,还是将 JSON 响应中的每个字段映射到新列?我的 SQL 技能有限,而且我研究过 MongoDB 之类的东西,但我现在已经有了与 Site5 的共享托管服务,我想使用它来保持它的便宜。
  • 有了这个长度,最好将 JSON 存储在数据库中。它不必是传统的基于列的 RDBMS - MongoDB 也可以。如果可能,您希望避免在服务器上存储单个文件。打开文件、读取或写入文件比从/向数据库读取和写入要耗费更多的 I/O。

标签: php angularjs


【解决方案1】:

如果您在服务中执行此操作,并且仅通过单击视图按钮调用方法,则更像这样:

angular.module('app.services', [

])
  .service('MyService', function ($http) {
    var MyService = this;
    this.aggregatedData = { content: [], filename: null };
    this.apiUrl = 'https://example.com/api?userID=';
    this.saveUrl = 'saveJson.php';

    this.getData = function (url) {
      return $http.get(url + $stateParams.userID).then(function (response) {
        MyService.aggregatedData.content.push(response.data);
      });
    };

    this.saveData = function (url, fileName) {
      this.aggregatedData.filename = fileName;
      return $http.post('saveJson.php', this.aggregatedData).then(function () {
        // do something with the post response if desired
      });
    };
  })

然后通过让控制器调用服务方法来连接视图中的按钮以获取和保存。

【讨论】:

    猜你喜欢
    • 2018-11-24
    • 2022-01-09
    • 1970-01-01
    • 2022-12-16
    • 2013-12-07
    • 1970-01-01
    • 2014-03-29
    • 2021-09-08
    • 1970-01-01
    相关资源
    最近更新 更多