我试图将JSON数据从php backend.Json数据的第一个属性"stock_price“随机更改到我的角度前端,但是JSON数据的时间属性应该以秒为单位递增。这意味着
{
stock_price: 19,
time: 1
}接下来应该是
{
stock_price: 26,
time: 2
}就像这样。
当我使用browser/postman尝试这个精确的php脚本时,它会按照我的预期在每个页面刷新/Post请求中更新。
但是,当我在一个角度应用程序中安慰它时,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;
?>角app组件文件
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);
}
}发布于 2018-06-14 09:47:05
你必须从角度上传递time。如果在URL中使用body,则可以将其作为POST发送(在GET的情况下)
$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);
}发布于 2018-06-14 09:47:57
在会话中添加新值。目前,您每次都要添加0。在任何PHP文件中添加下面的代码,每次都尝试重新加载。
session_start();
$time = isset($_SESSION['time']) ? $_SESSION['time'] : 0;
$arr['time'] = ++$time;
$_SESSION["time"] = $time;
echo json_encode($arr);https://stackoverflow.com/questions/50853844
复制相似问题