nest.js模板中获取async异步返回的数据

采用async方式获取数据库中的数据,返回的是一个Promise。直接在模板中去解析Promise得到的会是一个Promise对象,而不是最终返回的结果,然后用{{message.name}}去解析是会失败的。

解决方法,所有async方法配套加上await。拿一个官网的例子。

https://docs.nestjs.com/providers

cats.controller.ts


import { Controller, Get, Post, Body } from '@nestjs/common';
import { CreateCatDto } from './dto/create-cat.dto';
import { CatsService } from './cats.service';
import { Cat } from './interfaces/cat.interface';

@Controller('cats')
export class CatsController {
  constructor(private readonly catsService: CatsService) {}

  @Post()
  async create(@Body() createCatDto: CreateCatDto) {
    this.catsService.create(createCatDto);
  }

  @Get()
  async findAll(): Promise {
    return await this.catsService.findAll(); // 官网demo没有添加await关键词
  }
}

 

一个真实小项目的例子

crashes.controller.ts

import { Controller, Get, Post, Body, Param, Render, Res } from '@nestjs/common';
import { CreateCrashDto } from './dto/create-Crash.dto';
import { CrashesService } from './crashes.service';
import { Response } from 'express';
import { Crash } from './interfaces/crashes.interface';

@Controller('Crashes')
export class CrashesController {
  constructor(private readonly crashesService: CrashesService) { }


  @Get('/:version/:user')
  @Render('index')
  async findVersionUser(@Param('version') version: string, @Param('user') user: string): Promise {
    let result = await this.crashesService.aggregateVersionAsync(version);
    let total = await this.crashesService.aggregateVersionCountAsync(version);

    return { message: result, total: total.length };
  }
}

index.hbs





  
  App


group count :{{ message.length}}

{{#each message}} {{/each}}
tip count
{{_id}} {{num}}

crashes.service.ts

import { Inject, Injectable } from '@nestjs/common';
import { Model } from 'mongoose';
import { CreateCrashDto } from './dto/create-crash.dto';
import { Crash } from './interfaces/crashes.interface';

@Injectable()
export class CrashesService {
  constructor(@Inject('Crash_MODEL') private readonly CrashModel: Model) { }

  async aggregateVersionCountAsync(version: string): Promise {
    return await this.CrashModel.aggregate([{ $match: { version } }]);
  }

  async aggregateVersionAsync(version: string): Promise {
    return await this.CrashModel.aggregate([{ $match: { version } },
    { $group: { _id: '$tip', num: { $sum: 1 }, crashes: { $push: '$_id' } } },
    { $sort: { num: -1 } }]).exec();
  }

  async findAllVersion(): Promise {
    return await this.CrashModel.aggregate([
      { $match: { _id: { $ne: '-1' }, version: { $ne: '' } } },
      { $group: { _id: '$version', num: { $sum: 1 } } },
      { $sort: { _id: -1 } }]).exec();
  }
}

 

 

你可能感兴趣的:(前端)