I am trying to get JSON data to my angular front end from php backend.Json data's first property "stock_price
" changes randomly, but the JSON data's time property should be increment with seconds. Which means that,
{
stock_price: 19,
time: 1
}
next it should be
{
stock_price: 26,
time: 2
}
like that.
When i try this exact php script with browser/postman , it updates in every page refresh/Post request as i expected.
But when i console it in an Angular app, the time
property doesn't change. time
is stick to 1.
What can i do, in order to get an updating json reply.
php file
<?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 app component file
export class AppComponent {
ngOnInit(){
this._helper.helperHelp()
.subscribe(res => {
console.log(res);
})
}
constructor(private _helper:HelperService){
setInterval(()=>{
this.ngOnInit(); },4000);
}
}
service class
export class HelperService {
constructor(private _http:HttpClient) { }
helperHelp(){
return this._http.get("http://localhost/restPHP/restphp.php")
.map(result =>result);
}
}
You will have to pass time
from Angular. You can send it as body
if you are using POST
otherwise in URL (in case of GET
)
PHP
$time = isset($_GET['time']) ? $_GET['time'] : 0; // change to $_POST in case of POST
Angular component
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);
});
}
}
service
helperHelp(time) {
return this._http.get(`http://localhost/restPHP/restphp.php?time=${time}`).map(result =>result);
}
Add the new value in session. currently, you are adding 0
every time. Add below code in any PHP file and try to reload every time.
session_start();
$time = isset($_SESSION['time']) ? $_SESSION['time'] : 0;
$arr['time'] = ++$time;
$_SESSION["time"] = $time;
echo json_encode($arr);