0

Its now 8 hours trying to solve a trivial issue & I can't believe it !

here below a script of angular service

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class GetStockDataService {

  constructor(public http:HttpClient) { }


  RequestData={"query":"{\n  stock{\n    history{\n      \n      low\n      high\n      demand\n    }\n  }\n}"}

getstockdata(){
  return this.http.post('http://localhost:3000/',this.RequestData)
}

}

and here is a component script which is calling that service

import { Component, OnInit } from '@angular/core';
import { GetStockDataService } from '../services/get-stock-data.service';
import { Platform } from '@ionic/angular';




@Component({
  selector: 'app-Stocks',
  templateUrl: 'Stocks.page.html',
  styleUrls: ['Stocks.page.scss']
})

export class StocksPage implements OnInit {

  constructor(private GetStockData:GetStockDataService , private platform : Platform) {}

  res:any

  ngOnInit(){

    this.getdata().subscribe(data=>{this.res=data});
    console.log(this.res)

  }
  getdata(){
    return this.GetStockData.getstockdata() }}   

WHY the "res" variable is always returning NULL ???? knowing that when I put the console log the variable inside there in the function in the subscription part .. it returns data but I can't make this variable global ... how could I do that ? I just want to get the data from the subscription to the "res" variable to use it the HTML file later .

Aboulezz
  • 11
  • 5
  • 3
    You need to look up how promises and asynchronous code work. – ThisIsNoZaku Jan 20 '20 at 01:22
  • 1
    See [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086/218196). My blog about about callbacks might also help: https://felix-kling.de/blog/2019/javascript-callbacks-misconceptions.html – Felix Kling Jan 20 '20 at 01:22
  • okay , what should i need to add here ? – Aboulezz Jan 20 '20 at 01:22

1 Answers1

2

Due to Async call, console.log(this.res) executes before server call is processed.

Change

this.getdata().subscribe(data=>
{
  this.res=data
});
console.log(this.res)

To

this.getdata().subscribe(data=>
  {
   this.res=data; 
   console.log(this.res)
  });
Mohamed Farouk
  • 1,089
  • 5
  • 10
  • okay that will console the data , I want to get the data out of the scope – Aboulezz Jan 20 '20 at 01:27
  • 2
    @Aboulezz: You can call any function and pass the data to it, to get it "out of the scope". What you cannot do is access the data before it was actually received, like what you are doing in your code atm. – Felix Kling Jan 20 '20 at 01:28
  • data is resolved out of scope in `this.res` but you need to wait till server call is processed or otherwise `this.res` will be null – Mohamed Farouk Jan 20 '20 at 01:28