- When I console.log ("My ID is:") in the constructor, it prints out the correct ID generated by the server.
- 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