Why are the class variables in my Angular service not being stored properly in the injected class?

  1. When I console.log ("My ID is:") in the constructor, it prints out the correct ID generated by the server.
  2. However, in getServerNotificationToken() function, this.userID is returned as 'undefined' to the server and also prints as such.

I am puzzled as to why my class is not saving its variables properly. According to my understanding of ES6 javascript, the usage of the 'this' keyword should be bound to the class itself regardless of which function it is used in.

Thank you for your help!

@Injectable({
  providedIn: 'root'
})
export class GamestateService {
  public socket: any;
  public userID: number;

  constructor(private firebaseMessaging: FirebaseMessaging, public navCtrl:NavController) {
    this.socket = io('http://192.168.1.3:3001');
    this.socket.on('push-client-id', (data) => {
      this.userID = data.id;
      console.log("My ID is:", this.userID);
    })
    this.getServerNotificationToken();
  }

  getID():number {
    return this.userID;
  }

  getServerNotificationToken() {
    console.log("In firebase messaging...");
    this.firebaseMessaging.getToken().then((token) => {
      console.log("Token received: ", token);
      let tokenResponseObj = {
        token,
        userId: this.userID
      }
      console.log("My user id:", this.userID);
      console.log("tokenResponseObj.userId:", tokenResponseObj.userId);
      console.log("tokenResponseObj.token:", tokenResponseObj.token);
      this.socket.emit('token-received', tokenResponseObj);
    });
  }
}

Expected Result: userID assigned by server Actual Result: undefined

Answer №1

ES6 arrow functions are always bound to the class they are defined in, unlike normal functions which are bound to the calling class.

It seems like you are calling getServerNotificationToken outside of the socket callback function. This may cause it to execute before the callback function has been executed, leading to userID not being set yet. To ensure that userID is set before calling getServerNotificationToken, place the call inside the callback function.

this.socket.on('push-client-id', (data) => {
  this.userID = data.id;
  console.log("My ID is:", this.userID);
  this.getServerNotificationToken();
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unexpected JSONP Parsing Issue Despite Correct JSON Data

I've implemented a Cross Domain AJAX request using JSONP, and it's working fine with CORS. However, I'm facing an issue with JSONP. I've checked other threads but couldn't find a solution for my case. Below is the code snippet: ...

Encountering Axios 404 error while trying to access the routes directory

My server.js file in Express and Node.js contains the bulk of my back-end code, except for my database config file. The file is quite lengthy, and I want to enhance maintainability by breaking it down into smaller modules that can be imported. To start t ...

Confirm that the dependency has been invoked using Sinon

I am currently working on testing whether a dependency has been called or not. Here is an example of my code: export default class vehicle { private builder: CarBuilder; constructor() { this.builder = CreateCar(); <- factory return fake data } crea ...

Eliminate inner margin from the canvas of a bar chart created with ChartJS

I am looking to use Chart.js to create a single stacked bar chart that visualizes progress towards a specific financial goal. I have added a dotted line on top of the chart to represent this goal amount. The issue I am facing is that there is unwanted pad ...

Steps to combine NativeScript and Angular CLI

Exploring the potential of integrating NativeScript with Angular CLI to develop applications for both web and native mobile platforms. I attempted to use Nathan Walker's NativeScript Magic, but encountered difficulties creating a fresh application wit ...

Best practice for importing pipeable RxJs operators in Angular CLI/WebPack rollup

In the earlier versions of Angular CLI, specifically those before 1.5.0, it was common practice to import all RxJs operators and statics into a single file for easy usage throughout the application. For example: rxjs-operators.ts // Statics import &apos ...

Is there a way to narrow down Drive API list results based on a specific domain that has write permission?

I am currently working on retrieving a list of files from the drive API using a service account, with permissions granted to a specific domain for editing. While I have successfully implemented this feature for individual emails, I am facing a challenge in ...

Display JSON element in Angular only once

Below is the code snippet: <ion-content padding> <h1>Datum: </h1> <ion-list> <ion-item *ngFor="let u of tecaj"> <h2>{{u.datum}}</h2> <h2>{{u.drzava}} | {{u.valuta}}</h2> ...

Click the button to instantly scroll to a particular word with highlighting, and with another click, jump to the next occurrence

In order to achieve the objective, simply click on a button that will search for and scroll to a specific word while highlighting it. The same button can be clicked again to find the next occurrence, and so on. If you need an example of how this works, ch ...

The asynchronous nature of how setInterval operates

I am working with a setInterval function that executes asynchronous code to make calls to the server: setInterval(()=> { //run AJAX function here }, 5000); In scenarios where the server does not receive a response within 5 seconds, there is a like ...

Seamless transition of lightbox fading in and out

Looking to create a smooth fade in and out effect for my lightbox using CSS and a bit of JavaScript. I've managed to achieve the fading in part, but now I'm wondering how to make it fade out as well. Here is the CSS code: @-webkit-keyframes Fad ...

Retrieve data from backend table only once within the bootstrap modal

How can I retrieve values from a table once a modal is displayed with a form? I am currently unable to access the values from the table behind the modal. Are there any specific rules to follow? What mistake am I making? I would like to extract the values ...

Having trouble figuring out how to load images into a div based on the current page location?

Looking for a solution to my problem - I have a navigation bar with a fixed div (A) on the far right side. The nav bar remains at the top of the page. There are 6 sections in the body of the page, each being 1200px tall divs. What I want is for a different ...

Searching for a streamlined approach to retrieve a segment of a string

I'm currently working with JavaScript and TypeScript. Within my code, I encountered a scenario where I have a string that might contain certain tags indicating importance or urgency. Here are a couple of examples: A: "Remind me to go to the store to ...

Encountering an obscure package error while attempting to install an NPM package

After running the following command on my node application: npm install --save-dev typescript I encountered this error message: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="563a3f3426271667786e786e">[email pro ...

Tips for transitioning the li class from active to none

Struggling with changing the li class (of Home) from 'active' to none (or another class) when clicking on the profile tab, and then changing the li class (of Profile) from none to 'active' when the profile is activated. Snippet of my c ...

Bypass Security Check in Firefox

I am facing issues while trying to automate selenium on a website owned by a third party. When an authentication prompt like this appears in Firefox, Selenium fails: https://i.sstatic.net/VHQB4.png You can see a similar situation when clicking the Displ ...

Retrieving an image from an input file and setting it as the background of a div element

I am currently developing a whack the mole game using Vanilla JS, and I'm attempting to allow players to choose their own target by uploading an image file. However, despite days of searching for a solution, I have not been successful. HTML: <inpu ...

Unable to transform undefined or null into an object within Next.js

Hi there! Currently, I am working on creating a login page using Next.js and next-auth. I have included the necessary providers in the providers array within [...nextauth].js. However, when I attempt to run the following code: import { getProviders, signIn ...

Discover the steps to dynamically alter the inclusion of the Bootstrap CSS file within an Angular project

I manage a multi-language website in both English (EN) and Arabic (AR). Currently, I am utilizing Bootstrap CSS from a CDN and adjusting the CDN link based on the selected language. index.html <!DOCTYPE html> <html lang="en"> <h ...