Unable to load data inside ngOnInit

前端 未结 4 773
感情败类
感情败类 2021-01-26 10:31

My goal is to load a dropdown when a component renders. I have a service which hits a url and gets json data. Something like this

 @Injectable()
 export class St         


        
4条回答
  •  闹比i
    闹比i (楼主)
    2021-01-26 10:47

    As Amit mentioned, since this is an async call, your data won't be available untill the subscribe block runs. So you won't be having access to data outisde it

    Read the comments in the below code to understand:

    export class StudentListComponent implements OnInit {
      items: any = [];
    
      constructor(private studentListService: StudentListService) {}
    
      ngOnInit() {
        this.studentListService.getStudent().subscribe(
          data => {
            this.items = data;
            //////////  Here this.items WILL BE DEFINED
          },
          err => console.error(err),
          () => console.log('Done Loading Student Data'));
    
        //////////  Here this.items WILL BE undefined as this will run synchronously i.e. it won't wait for this.studentListService.getStudent() to run.
    
      }
    
    }
    

提交回复
热议问题