2

I am trying to use the Google Analytics API via Angular. I load the analytics script first

<script src="https://apis.google.com/js/client.js"></script>

I then console.log the global gapi variables that the api script creates. This returns the object as I'd expect, with an auth property. However gapi.auth appears undefined.

When I make the function wait two seconds though it does run as expected. This illustrates what happens:

enter image description here

However all the properties are there even in the first object:

enter image description here

Why does the later one have a preview and the earlier one doesn't? I'd imagine that this is related to why I can only access their properties after 2 seconds.


UPDATE:

I have added this checker at the top of my script to wait for gapi.auth to load... but it never finishes:

while (gapi.auth === undefined) {
    console.log("Still undefined");
}
console.log(loaded now");

enter image description here

Aron
  • 8,696
  • 6
  • 33
  • 59
  • I am not entirely sure I understand your question. But the lib isn't going to request auth info until you actually make a request against the api and the api will take a few seconds to respond. – Linda Lawton - DaImTo May 09 '16 at 12:41
  • My question is why the gapi.auth initially logs as undefined when gapi clearly has an auth property – Aron May 09 '16 at 12:42
  • Does it? [jsfiddle](https://jsfiddle.net/orpcmt8e/) – Mark C. May 09 '16 at 13:10
  • Yep, you can see on the second screenshot that it has an auth property in both cases. Only in the second one does it log out by itself though – Aron May 09 '16 at 13:11
  • "*Why does the later one have a preview and the earlier one doesn't?*" - it does. The preview is `{}` - the object was empty at the time it was logged. – Bergi May 09 '16 at 14:02
  • Ok I understand. But then why does my while loop checker never finish looping? (see my question update) – Aron May 09 '16 at 14:14

1 Answers1

0

the console.log function does not immediately evaluate the object given as arguments. It is evaluated only when you view or expand the object in the log window. So if your object changes it's properties by the time. You will see the snapshot of the object when you first open the log and try to expand the object. That's why when you open it too early, you see an empty object.

sohan nohemy
  • 615
  • 5
  • 13
  • Can you give a reference to what you said? – v7d8dpo4 May 09 '16 at 13:25
  • But that doesn't explain why when I create a while loop to check that gapi.auth === undefined it never ends. – Aron May 09 '16 at 13:30
  • Because gapi.auth is initialized when you exit from the while loop. Actually gapi.auth is loaded asynchronously. An asynchronous function can't be executed until you relinquish control to the system from your function. You need to know how java script event queue works. – sohan nohemy May 10 '16 at 12:13