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

Looking for a drag-and-drop solution using Vanilla Javascript, no need for jQuery

Looking for assistance with creating a click-and-drag solution for a background image using Vanilla Javascript. I came across a jQuery solution on Codepen, but I need help translating it into Vanilla Javascript. Draggable.create(".box", { ...

Nesting maps in JavaScript is a powerful way to transform

I'm in the process of developing a budgeting app using React and JavaScript. At the moment, I have successfully generated a table displaying various costs. Name Budget Used $ Used % Available Food 300 300 100 0 Streaming services 600 600 100 ...

Module Z encountered an unforeseen issue with the import of value X while utilizing the --aot flag

My application experiences significant slowness while loading in the browser (not to mention on mobile, taking 10-15 seconds). Even after running ng build --prod, the performance remains an issue. Attempting to address this with Angular CLI beta 16, I tri ...

What is the purpose of returning a function in a React Hook?

Currently, I am incorporating Material-UI components into my project and have implemented the AutoComplete component in my application. While exploring an example provided by the Material-UI team, I stumbled upon a fascinating instance of using Ajax data ...

The removeClass method does not affect the class attribute when using $(this).attr('class'), but only when using $(this).attr('id')

I am currently facing an issue with reducing the size of my jQuery code. The main function is to validate a form - if empty, I want to add a class of 'highlight' or remove it using addClass('highlight') and removeClass('highlight&a ...

After developing a React application to fetch data from my own API, I encountered the following error message: "TypeError: video.map is not a function". See the code snippet below:

import React, {useEffect, useState} from "react"; import Axios from "axios"; const VideoPage = () => { const [video, setVideo] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { const fetchVideoData = async() => ...

Reactify TypeScript: Accurate typings for onChange event

How can I resolve the issues with types for target: { value: any, name: any }? The errors I encounter include Duplicate identifier 'any'. and Binding element 'any' implicitly has an 'any' type.. Additionally, why does the erro ...

Accessibility issues detected in Bootstrap toggle buttons

I've been experimenting with implementing the Bootstrap toggle button, but I'm having an issue where I can't 'tab' to them using the keyboard due to something in their js script. Interestingly, when I remove the js script, I'm ...

What's the most effective method for updating the title of the date header on MUI Date Picker?

Does anyone know how to customize the title of the Calendar in MUI Date Picker? I want to add a specific string to the display that shows the month and year, like "August 2014." https://i.stack.imgur.com/qgMun.png I've searched the API but couldn&ap ...

Error encountered during password reset in Auth0

I am currently working with Angular 2 and using lock version 10.8 in an attempt to implement a feature that allows users to change their password. I've been experimenting with the following method, which involves calling the Management API. In this me ...

Enhance the navigation scroll bar with a blur effect

I'm looking to create a navigation bar with a cool blur effect as you scroll. Everything seems to be working fine, except when I refresh the page the scrollbar position remains the same and window.pageYOffset doesn't give me the desired result. T ...

Having trouble with querySelector or getElementById not functioning properly?

Currently, I am in the midst of developing an experimental web application that features a quiz component. For this project, I have implemented a Python file to handle the questions and quiz functionalities. However, I have encountered an issue with the Ja ...

Tips for implementing validation in AngularJS

Could someone help me with AngularJS validation? I'm new to it and trying to make sure everything is correct. var app=angular.module('myApp',[]) app.controller('myController',function($scope){ $scope.clickMe = function(){ if($(& ...

Having trouble getting Angular ngIf to work with multiple matches?

I am facing an issue with my ngIf directive that has got me puzzled. Initially, my ngIf statement was functioning flawlessly like this. ngIf="this.offerFormGroup.get('identityTypeId').value == 4 However, now I need to extend it by adding mo ...

Struggling to dynamically update array values by comparing two arrays

I am faced with a scenario where I have two arrays within an Angular framework. One of the arrays is a regular array named A, containing values such as ['Stock_Number', 'Model', 'Type', 'Bill_Number'] The other arr ...

Utilizing Angular's Dynamic Component Import and Loading capabilities

Looking to develop a portal that can dynamically load Angular components without the need for explicit imports. I've heard about using ComponentFactoryResolver for this purpose, but hoping to have the ability to store components in separate files or r ...

Can two Angular element components be utilized simultaneously on a single page in Angular 6?

Currently, I'm attempting to host independent Angular elements that can be seamlessly integrated into a non-Angular webpage. Everything works perfectly fine when there's only one element on the page, but as soon as I try to load two or more, I en ...

Is there a way to display a foundation.css drop-down menu using jQuery?

After attempting to create a navigation bar using foundation.css, I encountered an issue where the sub-menu does not appear when hovering over it with the mouse. The main question at hand is how to display the sub-menu of test on this specific webpage. D ...

When trying to retrieve a value from a custom render function in React with TypeScript, an error occurs indicating that the value is not assignable to type 'ReactNode'

Recently, I attempted to develop a versatile swiper component using Next.js 13 (App Router) v13.4.12 along with TypeScript. However, I encountered an issue when trying to access data from the component props, which involves a custom function for rendering ...

Looking for a way to prevent anonymous functions in jQuery using Greasemonkey?

Is there a way to prevent the execution of this particular jquery function? I've tried various scripts and even wrote my own, but nothing seems to work. $(document).ready(function () { $(window).on('beforeunload', function() { re ...