【问题标题】:How to iterate over array of js objects and display List Selector in google assistant app using google actions sdk如何使用谷歌操作sdk迭代js对象数组并在谷歌助手应用程序中显示列表选择器
【发布时间】:2017-07-25 04:42:28
【问题描述】:

我在这里搜索了所有文档 https://developers.google.com/actions/assistant/responses

在“列表选择器”的文档中,所有示例都使用静态和固定数量的数据。 对于一个真实的场景,我正在调用一个 RestAPI 并在 js 对象中获取响应,该对象具有我想要迭代的对象数组并在列表选择器中显示该信息。

以下是google assistant的action sdk文档中给出的List Selector示例。

function list (app) {
app.askWithList(app.buildRichResponse()
.addSimpleResponse('Alright')
.addSuggestions(
  ['Basic Card', 'List', 'Carousel', 'Suggestions']),
// Build a list
app.buildList('Things to learn about')
// Add the first item to the list
.addItems(app.buildOptionItem('MATH_AND_PRIME',
  ['math', 'math and prime', 'prime numbers', 'prime'])
  .setTitle('Math & prime numbers')
  .setDescription('42 is an abundant number because the sum of its ' +
    'proper divisors 54 is greater…')
  .setImage('http://example.com/math_and_prime.jpg', 'Math & prime numbers'))
// Add the second item to the list
.addItems(app.buildOptionItem('EGYPT',
  ['religion', 'egpyt', 'ancient egyptian'])
  .setTitle('Ancient Egyptian religion')
  .setDescription('42 gods who ruled on the fate of the dead in the ' +
    'afterworld. Throughout the under…')
  .setImage('http://example.com/egypt', 'Egypt')
)
// Add third item to the list
.addItems(app.buildOptionItem('RECIPES',
  ['recipes', 'recipe', '42 recipes'])
  .setTitle('42 recipes with 42 ingredients')
  .setDescription('Here\'s a beautifully simple recipe that\'s full ' +
    'of flavor! All you need is some ginger and…')
  .setImage('http://example.com/recipe', 'Recipe')
)
);
}

现在,当我在 .addItems() 之前在 js 对象数组上添加迭代器时,会显示语法错误,因为我们无法在其上方添加任何行。

当我们不能在 .addItems() 上面写任何东西时,我们如何在这里迭代并执行 .addItems() 有什么想法吗?

【问题讨论】:

    标签: javascript android arrays node.js actions-on-google


    【解决方案1】:

    在 app.askWithList() 之外创建列表后,如下所示,这很容易。

    function parseAndShowMessages(app, data) {
    let list = app.buildList('test Messages')
    for (var i = 0; i < data.response.messages.length; i++) {
      list.addItems(app.buildOptionItem(data.response.messages[i].subject,'')
        .setTitle(data.response.messages[i].from_name)
        .setDescription(data.response.messages[i].subject + '  \n' + data.response.messages[i].body)
        .setImage(IMG_URL_PICTURE,data.response.messages[i].subject)
      )
    }
    
    if (data.response.messages.length > 1) {
      app.askWithList(app.buildRichResponse()
        .addSimpleResponse('Sure, Below are your messages.')
        .addSuggestions(['Appointments']),list);
    }
    }
    

    上面的data是RestAPI的responsejs对象,data.response.messages有一个js对象数组。

    注意:根据actions sdk,列表选择器中必须至少有两个具有不同标题的项目。

    【讨论】:

      猜你喜欢
      • 2018-07-13
      • 2017-10-22
      • 2018-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多