【问题标题】:How to show data in a hbs template?如何在 hbs 模板中显示数据?
【发布时间】:2019-04-02 17:04:36
【问题描述】:

需要一些帮助,我正在尝试在模板中显示数据,但它不起作用。我将 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车把模板的代码:

<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>

即使在控制台日志中也可以显示数据。

【问题讨论】:

    标签: javascript node.js typescript handlebars.js nestjs


    【解决方案1】:

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

    我建议你的方法async:

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

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

    【讨论】:

    • 谢谢,它有效!我从这个框架开始。
    • 我很高兴它现在对你有用。欢迎来到 Stackoverflow。 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-29
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 2019-09-19
    相关资源
    最近更新 更多