如何创建类似“ context.Provider” /“ context.Consumer”的结构以在机器人应用中传递值?

时间:2019-04-05 19:12:42

标签: javascript node.js azure botframework bots

我试图将一个对象数组的第一个位置内的属性传递给另一个模块,以便以后可以使用该值。我尝试将其作为module(args)传递,但它始终读取默认值0。有没有办法做到这一点?

我尝试实现一些React.context,但是Bot框架仿真器拒绝了它。

/////////////////Module that ll acquire the value/////////////////////////////
    getCard(bot, builder, params) {
        let configValues = { ...params[0] }

        bot.dialog(`${configValues.path}`, function (session) {
            var msg = new builder.Message(session);

            const cardItem = (obj) => {
                return (new builder.HeroCard(session)
                    .title(`${obj.title}`)
                    .text(`R$ ${obj.price}`)
                    .images([builder.CardImage.create(session, `${obj.img}`)])
                    .buttons([
                        builder.CardAction.imBack(session, `${obj.price} Item adicionado!`, 'add to cart')
                        // !onClick event must add the current obj.price to 
                        // the configValues.total(Ex: configValues.total += obj.price)!
                    ])
                )
            }
            msg.attachmentLayout(builder.AttachmentLayout.carousel)
            msg.attachments(
                eval(params.map(obj => cardItem(obj)))
            );
            //!in here before end the dialog is where i want to update
// the configValues.total so i can show it in the -> Checkout module
            session.send(msg).endDialog()
        }).triggerAction({ matches: configValues.regex });
    }
}
//////////////CheckOut.Module///////////////////////////////
{...}
let configValues = { ...params[0] }
    let state = {
        nome: "",
        endereco: "",
        pagamento: "",
        total: configValues.total // this is the value to be read
    }

    bot.dialog('/intent', [
        {...},
        (session, results) => {
            state.pagamento = results.response
            session.send(
                JSON.stringify(state) // here is the place to be printed
            )
        {...}   
    ]
    ).triggerAction({ matches: /^(finalizar|checar|encerrar|confirmar pedido|terminar)/i })

1 个答案:

答案 0 :(得分:0)

自从您解决了原始问题以来,我将在您的评论中回答。

您的问题在这里:

cartId.map((obj, i , arr) => {
            // if (!obj.total) {
            //     obj.total.reduce(i => i += i)
            // }
            const newtotal = new total
            newtotal.getTotals(bot, builder, obj, arr)
        })

cartId包含您每个项目的总计。当您在其上调用map时,就是将每个项目分别传递到getTotals,后者将每个项目传递给checkout()

不能将所有总数相加,而只能对一个项的总数求和的原因是,您将cartId传递给checkout,而cartId已被更改为单个项。相反,您可以执行几项不同的操作:

  1. cartId传递整个cartItems,并在for (var key in cartItems)totalConstructor()中使用类似checkoutConstructor()的东西。这可能是最简单的方法,但不是很高效的内存。

  2. 使用BotBuilder's State Storagetotals数组存储在userData中,然后最后求和。这可能更难以实现,但是将是一条更好的选择。 Here's a sample可以帮助您入门。