首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >动态更新JSON数据

动态更新JSON数据
EN

Stack Overflow用户
提问于 2018-06-14 09:14:59
回答 2查看 309关注 0票数 0

我试图将JSON数据从php backend.Json数据的第一个属性"stock_price“随机更改到我的角度前端,但是JSON数据的时间属性应该以秒为单位递增。这意味着

代码语言:javascript
运行
复制
{
stock_price: 19,
time: 1
}

接下来应该是

代码语言:javascript
运行
复制
 {
stock_price: 26,
time: 2
}

就像这样。

当我使用browser/postman尝试这个精确的php脚本时,它会按照我的预期在每个页面刷新/Post请求中更新。

但是,当我在一个角度应用程序中安慰它时,time属性不会改变。time是坚持1。

我能做些什么,才能得到更新的json回复。

php文件

代码语言:javascript
运行
复制
<?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;
?>

角app组件文件

代码语言:javascript
运行
复制
export class AppComponent {


  ngOnInit(){
    this._helper.helperHelp()
    .subscribe(res => {
      console.log(res);
    })
  }

 constructor(private _helper:HelperService){
  setInterval(()=>{
    this.ngOnInit(); },4000); 
  }

 }

服务类

代码语言:javascript
运行
复制
export class HelperService {

  constructor(private _http:HttpClient) { }

  helperHelp(){
    return this._http.get("http://localhost/restPHP/restphp.php")
               .map(result =>result);
  }


}
EN

回答 2

Stack Overflow用户

发布于 2018-06-14 09:47:05

你必须从角度上传递time。如果在URL中使用body,则可以将其作为POST发送(在GET的情况下)

代码语言:javascript
运行
复制
$time = isset($_GET['time']) ? $_GET['time'] : 0; // change to $_POST in case of POST

角分量

代码语言:javascript
运行
复制
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);
        });
    }
}

服务

代码语言:javascript
运行
复制
helperHelp(time) { 
    return this._http.get(`http://localhost/restPHP/restphp.php?time=${time}`).map(result =>result); 
}
票数 1
EN

Stack Overflow用户

发布于 2018-06-14 09:47:57

在会话中添加新值。目前,您每次都要添加0。在任何PHP文件中添加下面的代码,每次都尝试重新加载。

代码语言:javascript
运行
复制
session_start();
$time = isset($_SESSION['time']) ? $_SESSION['time'] : 0;
$arr['time'] = ++$time;
$_SESSION["time"] = $time;
echo json_encode($arr);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50853844

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档