Search code examples
javascriptangularionic-frameworkionic3ionic4

Unable to fetch value in a variable


In home.ts, I am getting one value in a function. I need that value in a variable outside that function.

Below is home.ts code: unable to get the value of estimatedServerTimeMs in this.assignDate. It gives error.

assignDate;
ngOnInit() { 
      let epoch = firebase.database.ServerValue.TIMESTAMP;
      var offsetRef = firebase.database().ref(".info/serverTimeOffset");
      offsetRef.on("value", function(snap) {
      var offset = snap.val();
      var estimatedServerTimeMs = new Date().getTime() + offset;

      console.log(estimatedServerTimeMs); // enoch numeric string

      this.assignDate = estimatedServerTimeMs; // This is giving error
    });

}

Here is the error:

annot set property 'assignDate' of null
    at crud2.page.ts:60
    at index.cjs.js:4551
    at exceptionGuard (index.cjs.js:700)
    at EventList.push../node_modules/@firebase/database/dist/index.cjs.js.EventList.raise (index.cjs.js:9624)
    at EventQueue.push../node_modules/@firebase/database/dist/index.cjs.js.EventQueue.raiseQueuedEventsMatchingPredicate_ (index.cjs.js:9578)
    at EventQueue.push../node_modules/@firebase/database/dist/index.cjs.js.EventQueue.raiseEventsForChangedPath (index.cjs.js:9562)
    at Repo.push../node_modules/@firebase/database/dist/index.cjs.js.Repo.updateInfo_ (index.cjs.js:12698)
    at index.cjs.js:12690
    at each (index.cjs.js:556)
    at Repo.push../node_modules/@firebase/database/dist/index.cjs.js.Repo.onServerInfoUpdate_ (index.cjs.js:12689)

The problem is I am unable to take the value out of this function offsetRef.on("value", function(snap) {


Solution

  • Scope of this in function(snap) is denoting the function. Replace it with arrow function to use member variables.

    offsetRef.on("value", (snap) => {
      const offset = snap.val();
      const estimatedServerTimeMs = new Date().getTime() + offset;
    
      console.log(estimatedServerTimeMs); // enoch numeric string
    
      this.assignDate = estimatedServerTimeMs; // This is giving error
    });
    

    It is also a good practice to use let or const when declaring variables in Typescript instead of using var.