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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题