0

我有一个 API 调用,它为我获取一个随机图像。我正在尝试调用以下方法并尝试使用返回的变量,但它只会给我空结果。

  fetchRandomArt():RawImportData<Artdata>{

    var tempRand:RawImportData<Artdata> = new  RawImportData<Artdata>();
    this.dataService.getRandomArt<RawImportData<Artdata>>().subscribe(
      (res: RawImportData<Artdata>) => {
        if(res){
          tempRand = res;
          this.isLoading=false;
        }
      },
      err => {throw("Can't connect to Server.")}
    );
    console.log("tempRand");
    console.log(tempRand);
    return tempRand;

  }

但是我测试了 API 确实给了我结果(内部if(res)显示数据),但我无法在函数之外使用该数据。

另外,是否可以每 5 秒后自行执行此功能?

编辑:

我刚刚注意到,内部函数稍后执行,

out tempRand
RawImportData {}
in tempRand
{records: Array(1), pagination: {…}}

我知道我可以通过调用和订阅 n 次来解决这个问题,但我只想使用这个函数返回的值,因为我希望它能够自我调用。

更新

只想更新标记到此问题的链接不回答此问题,但是以下方法可以,

  public async fetchRandomArt():Promise<RawImportData<Artdata>>{
    const data = await this.dataService.getRandomArt<RawImportData<Artdata>>().toPromise();
    this.isLoading=false;
    console.log(data); 
    return data;
  }
4

0 回答 0