Home > Software engineering >  Why I receive information in the subscribe but it disappears after it?
Why I receive information in the subscribe but it disappears after it?

Time:01-24

I am programming a web, using Angular, and I have been for a long time testing a thing that does not work properly. I have a server that obtains the data of some translations:

  getTranslations(): Observable<Translation[]> {
    return this.http.get(`${this.baseUrl}/getAllTranslations.php`).pipe(
      map((res: any) => {
        return res['data'];
      })
    );
  }

And then, from the client side, I obtain the data doing this:

//Variables
  translations?: Translation[];

  constructor(private translationService: TranslationsService) { }

  ngOnInit(): void {
    this.getTranslations();
  }

  getTranslations(): void {
    this.translationService.getTranslations().subscribe((data: Translation[]) => {
      this.translations = data;
      console.log(this.translations);
    });
    console.log(this.translations);
  }

The thing is that if I print the results of translations inside the subscribe, I obtain the data, but the second console.log shows that the list of Translations is empty, and I do not know which is the problem. Can someone help me? The first log is:

0
: 
{id: '1', title: 'Franco. Unidos en la distancia'}
1
: 
{id: '4', title: 'La amiga'}

And the second is undefined. Thanks in advance!!

CodePudding user response:

The key concept here is that observables are asynchronous, so your code doesn’t wait for the observable to complete before the next line run.

In your case, the console log outside the observable loop is running before the console log inside the loop, but the local variables hasn’t been set.

CodePudding user response:

Use async and await or toPromise.

  getTranslations(): void {
    this.translations =  this.translationService.getTranslations().toPromise();
    console.log(this.translations);
  }
  • Related