简体   繁体   English

等待 Http 请求完成使用 NestJS

[英]Wait for Http Request to finish using NestJS

I'm using Angular + NestJS as a combination here and I'm trying to fetch some data from public API.我在这里使用 Angular + NestJS 作为组合,我正在尝试从公共 API 获取一些数据。 The case is that I can see the returned data from NestJS console but Angular-side returns empty JSON.情况是我可以看到 NestJS 控制台返回的数据,但 Angular 端返回空的 JSON。 The problem is that the frontend side won't wait for Http request to be finished and instead triggers console.log too early.问题是前端不会等待 Http 请求完成,而是过早触发 console.log。 I know that I need to wait for the response but how can I do so?我知道我需要等待回复,但我该怎么做?

app.component.ts: app.component.ts:

async listAnalyses() {
    await this.reportingService.listAnalyses().then(
        (data: any) => {
            console.log(data); // this is triggered too soon
        },
        (err: any) => {
            console.log(err);
        }
    )
}

reporting.service.ts:报告.service.ts:

listAnalyses() {
    return this.http.get(`${environment.api}/list-analyses`);
}

app.controller.ts: app.controller.ts:

 @Get('list-analyses')
 async listAnalyses() {
    let analyses;


    // params given here but hidden from the code (includes account data)
    await this.publicApi.listAnalyses(params, (err: any, data: any) => {
        if (err) {
            console.log(err);
        } else {
            console.log(analyses); // this logs real data in NestJS console, that's what I want in frontend side too
        }
    });

    return {
        analyses: analyses
    }
 }

How do I proceed from here?我该如何从这里开始?

You need to convert a callback syntax into a Promise syntax (or Observable one).您需要将回调语法转换为 Promise 语法(或 Observable 语法)。

 @Get('list-analyses')
 async listAnalyses() {
    return new Promise((res, rej) => this.publicApi.listAnalyses(
      params, (err: any, data: any) => {
        if (err) return rej(err);
        else return res(data);
      })
    );
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM