0

I have a component that calls on an endpoint to populate a variable of type List which is a List of PaperNames.

papers: paperNameDTO;

I populate papers on the page loading in ngOnInit:

     ngOnInit() {
            this.fileService.getPaperNames().subscribe(data => {
      console.log('Entering here API call');
      this.papers = data['papers'];
    });

    if(this.papers.papersList.length > 0) {
       console.log('Entering filteredPapers');
       const filteredPapers = this.papers.papersList.filter(paper => paper.name 
       !== 'FINAL_YEAR' && paper.name !== 'FIRST_YEAR' );
       console.log('Final length is = ' + filteredPapers.length);
      }
   }

The goal is to exclude returned Strings with names 'FINAL_YEAR' and 'FIRST_YEAR' which i filter into another array of Strings.

Problem i face is this method does not work, when i check the console logs, the loop if(this.tables.tables.length > 0) gets entered first before this.enquireService.getTableNames().subscribe(data =>. Why is that so? And how could i accomplish this otherwise?

JohnDoeDeer
  • 85
  • 1
  • 11

2 Answers2

1

Whenever a subscribe is used it means, sometime in the future something will happen. The code moves on to next statement where it immediately executes. If the next statement relies on a state inside the subscription it will not work. To fix, from the subscription call the function which need the data.

JWP
  • 6,672
  • 3
  • 50
  • 74
0

Any functionality that directly depends on an asynchronous data should be inside the subscription. Please see here for more details on how to access asynchronous data: https://stackoverflow.com/a/14220323/6513921

ngOnInit() {
  this.fileService.getPaperNames().subscribe(data => {
    console.log('Entering here API call');
    this.papers = data['papers'];
    const filteredPapers = this.papers.papersList.filter(
      paper => paper.name !== 'FINAL_YEAR' && paper.name !== 'FIRST_YEAR');
  });
}
ruth
  • 29,535
  • 4
  • 30
  • 57