javascript - 动态更新 JSON 数据
问题描述
我正在尝试从 php backend.Json 数据的第一个属性“”随机更改 JSON 数据到我的角度前端stock_price
,但 JSON 数据的 time 属性应该以秒为单位递增。意思就是,
{
stock_price: 19,
time: 1
}
接下来应该是
{
stock_price: 26,
time: 2
}
像那样。
当我使用 browser/postman 尝试这个确切的 php 脚本时,它会按照我的预期在每个页面刷新/发布请求中更新。
但是当我在 Angular 应用程序中对其进行控制台时,该time
属性不会改变。time
坚持1。
我该怎么做才能获得更新的 json 回复。
.php 文件
<?php
header('Content-Type: application/json');
session_start();
$time = isset($_SESSION['time']) ? $_SESSION['time'] : 0;
$stock_price = rand(10,100);
$arr['stock_price'] = $stock_price;
$arr['time'] = ++$time;
echo json_encode($arr);
$_SESSION['time'] = $time;
?>
Angular 应用程序组件文件
export class AppComponent {
ngOnInit(){
this._helper.helperHelp()
.subscribe(res => {
console.log(res);
})
}
constructor(private _helper:HelperService){
setInterval(()=>{
this.ngOnInit(); },4000);
}
}
服务等级
export class HelperService {
constructor(private _http:HttpClient) { }
helperHelp(){
return this._http.get("http://localhost/restPHP/restphp.php")
.map(result =>result);
}
}
解决方案
您将不得不time
从 Angular 传递过来。您可以像在 URL 中使用其他方式一样发送它(body
如果是)POST
GET
PHP
$time = isset($_GET['time']) ? $_GET['time'] : 0; // change to $_POST in case of POST
角组件
export class AppComponent {
stockData;
constructor(private _helper:HelperService){
}
ngOnInit(){
this.getDataFromServer();
this.scheduleInterval();
}
scheduleInterval() {
setInterval(this.getDataFromServer, 4000);
}
getDataFromServer() {
let time = this.stockData ? this.stockData.time : 0;
this._helper.helperHelp(time).subscribe(res => { //use time in your service
this.stockData = res;
console.log(this.stockData);
});
}
}
服务
helperHelp(time) {
return this._http.get(`http://localhost/restPHP/restphp.php?time=${time}`).map(result =>result);
}
推荐阅读
- python - 每次加入列表中的 4 位数字
- perforce - 如何在 Linux 上为命令行更新 Perforce 客户端工具
- python - 如何从 HTML 中获取特定表格
- .net - 无法启动 IIS 10 Express
- c# - 我需要将 C# 代码上的 Razor 块翻译成 VB.NET
- r - 创建新的重复索引,其中每个数字的范围尽可能有效地依赖于另一列的索引
- node.js - 让 Docker 与 Gulp 和 Browsersync 一起工作
- g++ - g++ 错误:无法使用 -fsanitize=address 指定 -static
- javascript - Angularjs $HTTP POST JSON 数据到服务器问题
- node.js - 在 node.js 中作为子进程运行 shell(bash, zsh, sh...)