0

I am using an HTTP GET request to retrieve some JSON code from my server. I store the JSON data in a variable. The JSON data only has two objects, minutes and seconds. Both objects are changing in value constantly (the JSON represents a timer). My problem is, if I interpolate the value in the HTML template, it comes out perfect! But if I try to console.log the JSON data, or store it into an array, it gives me either null, or Array, with no data in it.

this.timeService.fetchTime().subscribe(
    (data) => this.timeArray = data);
console.log(this.timeService);

This is the service that retrieves my JSON data, and stores it into an already declared variable timeArray = [ ]. If I use {{timeArray.minutes}} in my HTML code, it shows up fine. How do I store timeArray.minutes into a local variable in my code?

Tristan C
  • 593
  • 2
  • 7
  • 16
  • If you are able to use {{timeArray.minutes} that means you are already storing your data in a variable. Where is the problem exactly? Show the code that gives you null. – Sefa Oct 12 '16 at 19:06
  • If I type in console.log(this.timeService.seconds); I receive a typescript error saying 'Property seconds does not exist on type TimeService' – Tristan C Oct 12 '16 at 19:10
  • `this.timeService` is the class instance that you use for **getting** the data. In your callback, you **store** the data in `this.timeArray`. So try `console.log(this.timeArray.seconds)`. Note, that's **timeArray**, not **timeService**. – Travesty3 Oct 12 '16 at 19:14
  • https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call Not a angular/typescript problem, but a problem of combining synchronous and asynchronous code. – tcooc Oct 12 '16 at 19:19

1 Answers1

0

If it shows correctly in your template, then you already have it stored in a variable.

What you can do additionally is create another variable minutes and pass to it the minutes value from data.

this.timeService.fetchTime().subscribe(
(data) => {
    this.timeArray = data;
    this.minutes = data.minutes;
});
Alexander Ciesielski
  • 10,506
  • 5
  • 45
  • 66
  • For some reason, if I console.log the minutes var like you showed in this example, I get an "undefined" – Tristan C Oct 12 '16 at 19:16
  • You know that HTTP calls are asynchronous, right? You have to do the `console.log` after minutes is assigned with a value. Also, you should declare the variable just like you declared `timeArray` – Alexander Ciesielski Oct 12 '16 at 19:17