首页 > 解决方案 > 访问 JSON 实现值值

问题描述

我是Vue的新手,我正在使用电子 Vue 样板。我正在尝试使用NodeJS 中的Promise在 Amazon 中显示一些项目。我正在使用“ amazon-product-api ”,是的,我可以访问亚马逊产品广告 API。我已经在一个单独的 .js 文件中编写了我的代码,并在 Vue 组件中进行了链接。

这是我使用 amazon-product-api 获取 ItemSearch 的功能,

// This function will take take idea and give stats in return
// @input string
// @return json
function getKeywordStats (keyword, searchType, delay, domain) {
  // Setting URL and headers for request
  if (searchType === 0) {
    searchType = 'KindleStore'
  } else {
    searchType = 'Books'
  }

  if (domain === 'com') {
    domain = 'webservices.amazon.com'
  } else if (domain === 'de') {
    domain = 'webservices.amazon.de'
  } else if (domain === 'uk') {
    domain = 'webservices.amazon.uk'
  }

  var query = {
    keywords: keyword,
    searchIndex: searchType,
    sort: 'relevancerank',
    itemPage: 1,
    availability: 'Available',
    responseGroup: 'Large',
    domain: domain
  }
  return new Promise(function (resolve, reject) {
    amazonClient.itemSearch(query, function (error, results) {
      if (error) {
        console.log(error)
      } else {
        var title = results[0].ItemAttributes[0].Title[0]
        var imageUrl = results[0].ItemAttributes[0].Title[0]
        var data = {
          title: title,
          imageUrl: imageUrl
        }
        // console.log(results)
        // var noCompetitors = results.ItemAttributes.Items.TotalResults
        resolve(data)
      }
    })
  })
}

这是我的 Vue 组件,

<template>
    <div class='hello'>
        <p> {{data}} </p>
    </div>
</template>

<script>
/* eslint-disable no-unused-vars */
// ebook data - 0
// book data - 1

var amazon = require('../../controllers/amazon-service.js')

var keywordDictionary = {}

var getStats = amazon.getKeywordStats('trump aftershock', 0, null, 'de')
console.log()

export default {
  data () {
    return {
      data: [
        {
          terms: getStats
        }
      ]
    }
  }
}
</script>

<style>
.hello {
  color: blue
}
</style>

当我运行它时,我能够在我的 Vue 组件中显示承诺数据。这就是它在页面上的显示方式。

[ { "terms": { "isFulfilled": true, "isRejected": false, "fulfillmentValue": { "title": "Trump Aftershock: The President's Seismic Impact on Culture and Faith in America (English Edition)", "imageUrl": "Trump Aftershock: The President's Seismic Impact on Culture and Faith in America (English Edition)" } } } ]

但我无法获得“ fulfillmentValue ”。我将附上一些有助于解决此问题的屏幕截图。如果我做错了,请引导我走向正确的道路。

应用程序显示的内容 -

电子-vue响应

验证 JSON 响应 -

json有效

标签: javascriptvue.jspromiseamazon-product-apielectron-vue

解决方案


Amazon API 函数getKeywordStats返回一个Promise- 它是一个异步操作。这意味着该函数不会像正常的同步函数那样返回结果,而是返回一个Promise对象,然后您可以注册一个回调函数(通过then),以便在检索到数据后调用。请务必阅读承诺的工作原理;我不会在这里详细介绍,因为已经有很多关于它们的信息。

将 API 调用移动到您的组件created挂钩中:

export default {
  data() {
    return {
      terms: null
    }
  },

  created() {
    amazon.getKeywordStats('trump aftershock', 0, null, 'de').then(terms => {
      this.terms = terms
    })
  }
}

推荐阅读