dowb58485 2016-01-19 18:31
浏览 53

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

I'm trying to create an app in AngularJS that aggregates data from multiple APIs. With some public APIs there are request limits and much of the data I want to pull is not updated very frequently, so only one request a month for a particular ID is necessary. To get past this, I've set up a Factory that first checks for a local file on the server, if it is not present, it then goes to the API and performs a GET request.

From there, once the request is complete, I want to save that file to the server with a name set by a field in the response.

I've found some examples using PHP with AngularJS but I'm not sure on how to save the JSON file with the dynamic name...or if this is even the best thing to do in order to avoid the request limits.

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);
?>
  • 写回答

1条回答 默认 最新

  • doujiong9915 2016-01-19 18:59
    关注

    If you do this in a service, and just call a method from a view button click, it would be more like this:

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

    Then wire up buttons in your view to fetch and save by having the controller call the service methods.

    评论

报告相同问题?

悬赏问题

  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能