クラスが変数をクラスに保存しないのはなぜですか?ES6 javascriptについての私の理解は、 'this'キーワードは、使用されている関数に関係なく、クラス自体にバインドされているということです。
ありがとう!
@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);
});
}
}
予期されるもの:サーバーによって割り当てられたuserID#結果:未定義
ES6矢印関数のみが常に定義されているクラスにバインドされ、通常の関数ではなく、呼び出し元のクラスにバインドされます。
ソケットコールバック関数の外部でgetServerNotificationTokenを呼び出しているため、コールバック関数が実行される前に実行されている可能性があります。したがって、userIDはまだ設定されています。getServerNotificationToken呼び出しをコールバック関数に入れると、呼び出される前にuserIDが設定されていることが保証されます。
this.socket.on('push-client-id', (data) => {
this.userID = data.id;
console.log("My ID is:", this.userID);
this.getServerNotificationToken();
})
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加