Search code examples
angulartypescriptsubscribe

How can i subscribe data with forkJoin in angular 10?


I am working on an angular project , i have one component where i should get data from different endpoints so i figured out that i can do that with forkJoin which was working but now nothing works even a simple console.log and i don't get any errors . This is my code:

 ngOnInit(): void {


 let summary = this.covidService.getSummary() ; 
 let lastDays=this.covidService.getSevenLastDays() ; 
 let getDataSince = this.covidService.getDataSince() ; 
 let getAllNews = this.covidService.getAllNews() ; 

 this.user = this.covidService.getUser() ;


  forkJoin(summary , lastDays , getDataSince , getAllNews).subscribe(([call1Response , call2Response 
   , call3Response , call4Response])=>{


  console.log("Hello world ") ; 

 
 }) ; 


}

Solution

  • The method being used in the question is deprecated, so yes it would work for now, but could break in the future. The correct method is to pass an array of Observables or an Object of observables into the forkJoin.

    I think you want to do it like this:

    ngOnInit(): void {
    
        let summary = this.covidService.getSummary() ; 
        let lastDays=this.covidService.getSevenLastDays(); 
        let getDataSince = this.covidService.getDataSince(); 
        let getAllNews = this.covidService.getAllNews(); 
    
        this.user = this.covidService.getUser();
    
    
        forkJoin([summary , lastDays , getDataSince , getAllNews]).subscribe(response => {
            response.forEach(_response => console.log(_response);
        }); 
    }
    

    You could also do it like this:

    ngOnInit() : void { 
        this.user = this.covidService.getUser();
    
        forkJoin({
            summary: this.covidSerivice.getSummary(),
            lastDays: this.covidService.getSevenLastDays(),
            getDataSince: this.covidService.getDataSince(),
            getAllNews: this.covidService.getAllNews()
        }).subscribe(response => {
            console.log(response.summary);
            console.log(response.lastDays);
            console.log(response.getDataSince);
            console.log(response.getAllNews);
        }
    }