使用 AngularJS 将 API 响应保存到服务器作为 JSON 文件


Save API response to server as JSON file with AngularJS

我正在尝试在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);
?>

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

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
      });
    };
  })

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