首页 > 解决方案 > 动态更新 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);
  }


}

标签: javascriptphpjsonangularrest

解决方案


您将不得不time从 Angular 传递过来。您可以像在 URL 中使用其他方式一样发送它(body如果是)POSTGET

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

推荐阅读