I am trying to add the username from the user who signed to populate a data field of a form. I got the username however it isnt being placed in the variable to be posted to the database. The function is as follows:
addMessage() {
this.mocsignup.getUserProfile().subscribe((res) => {
this.mocUserDetails = res['user'];
});
let userDetail = this.mocUserDetails.username;
console.log(userDetail);
let formData: any = {
username: this.form.value.userDetail,
message: this.form.value.message,
}
this.messageService.postMessage(formData).subscribe((d) => {
console.log(d);
});
//window.location.reload();
}
This piece of code gets the username and saves it to the userDetail
variable that is verified by the console.log results:
this.mocsignup.getUserProfile().subscribe((res) => {
this.mocUserDetails = res['user'];
});
let userDetail = this.mocUserDetails.username;
console.log(userDetail);
console.log results:
This is the intended results.
however when trying to post to the database using the following code:
let formData: any = {
username: this.form.value.userDetail,
message: this.form.value.message,
}
this.messageService.postMessage(formData).subscribe((d) => {
console.log(d);
});
It does not pust to the username
in the collection, instead it skips it and sends the message and messageDateTime:
It is supposed to have a username
field stored in the results above doesnt.
Please help!
CodePudding user response:
Note that you have 2 different userDetail
variables:
- One that you created with
let userDetail = this.mocUserDetails.username;
- One in a form
this.form.value.userDetail
You are storing data in the first one, but later you are referencing the second one in the formData
. Try changing your code like this:
let formData: any = {
username: userDetail ,
message: this.form.value.message,
}
CodePudding user response:
If you're getUserDetails()
is doing a api call then that method would be an asynchronous one, if that's the case the the code won't be waiting for the api to give back the userName and it'll skip to next block of statements. So if you want to use the results of getUserDetails()
then move the statements within the method's block, like this
this.mocsignup.getUserProfile().subscribe((res) => {
this.mocUserDetails = res['user'];
let userDetail = this.mocUserDetails.username;
console.log(userDetail);
});