我如何在 angular 10 中使用 forkJoin 订阅数据?

How can i subscribe data with forkJoin in angular 10?

我正在做一个 angular 项目,我有一个组件,我应该从不同的端点获取数据,所以我发现我可以用 forkJoin 来做到这一点,它正在工作,但现在没有任何工作,即使是一个简单的console.log 而且我没有收到任何错误。这是我的代码:

 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 ") ; 

 
 }) ; 


}

试试这个代码看看它是否有任何控制台错误

forkJoin(summary , lastDays , getDataSince , getAllNews).subscribe(
  function (x) {
    console.log('Next: %s', x);
  },
  function (err) {
    console.log('Error: %s', err);
  },
  function () {
    console.log('Completed');
  });

问题中使用的方法已被弃用,所以是的,它现在可以使用,但将来可能会中断。正确的方法是将一个 Observables 数组或一个 Object of observables 传递给 forkJoin。

我想你想这样做:

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);
    }); 
}

你也可以这样做:

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);
    }
}