javascript - 如何在 hbs 模板中显示数据?

标签 javascript node.js typescript handlebars.js nestjs

需要一些帮助,我正在尝试在模板中显示数据,但它不起作用。我将 NestJS 与 mysql 结合使用。

这里是controller.ts的代码:

import { Controller, Get, Post, Put, Delete, Body, Param, Render, UsePipes, Logger, UseGuards} from '@nestjs/common';
import { ProductoService } from './producto.service';
import { ProductoDTO } from './producto.dto';
import { ValidationPipe } from '../shared/validation.pipe';


@Controller('producto')
export class ProductoController {
    private logger = new Logger('ProductoController');

    constructor(private productoService: ProductoService){}

    @Get('index')
    //@UseGuards(new AuthGuard())
    @Render('Producto/index')
    showAllUsers(){
        return {product:this.productoService.showAll().then(function(result){
            var aux = [{}];
            aux = result;
            console.log(aux);
            return aux;

        })};        
    }
}

这里是 index.hbs handlebars 模板的代码:

<h2>Lista de Productos</h2>
<div class="entry">
    <table class="table">
        <tr>
            <th>Nombre</th>
            <th>Cantidad</th>
            <th>Descripcion</th>
            <th></th>
        </tr>
        <tr>           
            {{#each aux}}
                <td>{{this.name}}</td>
                <td>{{this.quantity}}</td>
                <td>{{this.description}}</td>
            {{/each}} 
        </tr>
    </table>
    <br/>
</div>

甚至在控制台日志中显示数据。

image data log

最佳答案

我不认为 nestjs 会自动等待嵌套的 promise 解决。所以它将返回 {product: Promise}

我建议让你的方法async:

@Get('index')
async showAllUsers(){
    const products = await this.productoService.showAll();
    return {products};        
}

此外,在您的 hbs 模板中,您指的是 aux,尽管您返回了 {product: [...]}。所以它应该是 {{#each product}} 代替。 (在上面的示例中,我已将其重命名为 products,因为它是一个数组。)

关于javascript - 如何在 hbs 模板中显示数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53051033/

相关文章:

javascript - HTML/Jquery 如何限制子 div 的数量?

javascript - 如何通过js小写所有字符和大写第一个字符?

javascript 如何动态获取高度(当我调整浏览器大小时)

node.js - Angular 5 不会部署到 Azure 应用服务

typescript - 创建以前的类型

javascript - 需要在一个 onDateChange 上调用 2 个不同的函数

node.js - Mongoose - 根据 bool 属性对查找进行排序

node.js - 在 AWS Lambda 中创建 RESTful 服务

javascript - 使用 nestjs 将 hbs 渲染保存到变量中

javascript - 使用@nestjs/graphql 使用@ResolveProperty 和@Resolvers 创建嵌套查询