[英]How to iterate over array of js objects and display List Selector in google assistant app using google actions sdk
我在這里https://developers.google.com/actions/assistant/responses中搜索了所有文檔
在“列表選擇器”的文檔中,所有示例均使用靜態和固定數量的數據。 對於實際情況,我正在調用RestAPI並在js對象中獲取響應,該對象具有要迭代的對象數組,並在列表選擇器中顯示該信息。
以下是Google助手的動作sdk文檔中給出的列表選擇器示例。
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對象數組上添加迭代器時,顯示了syntex錯誤,因為我們無法在其上方添加任何行。
當我們無法在.addItems()之上編寫任何內容時,關於如何在此處進行迭代並執行.addItems()的任何想法?
一旦在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);
}
}
上面的數據是RestAPI的響應js對象,而data.response.messages具有一個js對象數組。
注意:根據sdk動作,列表選擇器中必須至少有兩個標題不同的項目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.