Php 使用AngularJS将对服务器的API响应保存为JSON文件
我正在尝试在AngularJS中创建一个应用程序,它可以聚合来自多个API的数据。对于一些公共API,有请求限制,并且我想要获取的大部分数据都没有频繁更新,因此每个月只需要对特定ID请求一次。为了解决这个问题,我建立了一个工厂,首先检查服务器上的本地文件,如果它不存在,它就会转到API并执行get请求 从那里,一旦请求完成,我想用响应中的字段设置的名称将该文件保存到服务器 我发现了一些使用PHP和AngularJS的例子,但我不确定如何用动态名称保存JSON文件……或者这是否是避免请求限制的最好方法Php 使用AngularJS将对服务器的API响应保存为JSON文件,php,angularjs,Php,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
如果您在服务中执行此操作,只需从视图按钮单击调用一个方法,它将更像这样:
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
});
};
})
然后连接视图中的按钮,让控制器调用服务方法来获取和保存。您从第三方API得到的响应有多大?如果字符数减少到几千或更少,您可以将JSON字符串存储在数据库中,而不是在服务器上创建单独的文件。在大多数情况下,是的,每个JSON响应可能在500-3000个字符之间。您的想法是将整个JSON响应存储在数据库的一列中,还是将JSON响应中的每个字段映射到一个新列?我的SQL技能有限,我也看过类似MongoDB的东西,但我现在已经有了一个与Site5共享的托管服务,我想用它来保持便宜。有了这个长度,最好将JSON存储在数据库中。它不必是传统的基于列的RDBMS,MongoDB也可以工作。如果可能,您希望避免在服务器上存储单个文件。打开文件、读或写文件比从数据库读和写文件要耗费大量的I/O资源。
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
});
};
})