首页 > 解决方案 > 从 subscribe() Angular 7 中获取价值

问题描述

我已经测试了不同的解决方案,例如添加地图或 switchMap 但我迷路了,我仍然无法从服务功能的订阅中获取数据。

我有服务功能:

getAllExperiments (): Observable<Experiment[]> {
   return  this.http.get<Experiment[]>(this.urlEndPoint)
     .pipe(
       catchError(this.handleError<Experiment[]>('getExperiments', []))
     );

   }

和中的调用ngOnInit

async ngOnInit() {
      await this.experimentService.getAllExperiments()
      .subscribe( response => {
        this.expTable = response
        this.expId = this.expTable.length;
        console.log(this.expTable, this.expId) //appears after the other console.log but with the values
      })
      console.log(this.expId) //appears first and undefined

      await this.experimentService.getExperiment(this.expId)
      .subscribe(response => {
        this.experiment = response
      });

      await this.compareService.getScore(this.expId)
      .then(response => {
        this.expScore = response;
      })

    }

  }

显然getExperiment带有 ID 的功能也不能正常工作。

我知道它应该能够与 a 一起使用,toPromise但我不知道如何在这里使用它。

标签: angulartypescript

解决方案


1) ngOnInit 不是异步的,所以await从文件中删除。

2)如果您想连接更多请求,您应该使用forkJoin示例)。

3)如果您需要第一次请求使用的数据switchMap例如

this.service.methodA(paramA).pipe(
switchMap((resA)=>this.service.methodB(resA.paramB))
).subscribe((resB)=> {...});

推荐阅读