0

At line 16 i change the value of email. At line 17 i can print the correct value of the email. But, why at line 20 i can't print the new value of the email? At line 20 the console.log prints the value of email at line 5 (''). I'll need the value of email at line 22. How can i do that?

1. export class SettingsComponent implements OnInit {
2.  private token: string | null = '';
3. public settings! : Settings;
4. public settingsForm!: FormGroup;
5. public email: string | null = '';

6. constructor(
7. private SettingsService: SettingsService,
8. private formBuilder: FormBuilder) { }

9. ngOnInit(): void {
10. this.token = localStorage.getItem('token');
11. if (this.token){
12.    this.SettingsService
13.         .getSettings(this.token)
14.         .subscribe(res => {
15.           this.settings = JSON.parse(JSON.stringify(res));
16.           this.email = this.settings.email;
17.            console.log(this.email);
18.         },err => {
19.            console.log(err); })
    }
20.  console.log(this.email);
21.    this.settingsForm = this.formBuilder.group({
22.       email: [this.email]
    });

  }

I want to change the value of an property and then use this value later.

  • You are trying to access an asynchronous retrieved value synchronously. Line 20 simply reads it before the asynchronous process returned. – MoxxiManagarm Nov 09 '22 at 16:12
  • 1
    See the aforementioned [suggested duplicate](https://stackoverflow.com/q/14220321/1260204). Asynchronous calls are a common and critical building block in writing/designing an application. It is critical that you understand how to work with asynchronous calls in javascript, and by extension typescript. Understanding these core concepts will help you become a better programmer and also ensure you do not keep "stubbing your toe" on the same problem. – Igor Nov 09 '22 at 16:16

0 Answers0