javascript - 如何使用 vanilla javascript 将 api 调用的数据存储到 firestore 数据库?

标签 javascript google-cloud-firestore

我从 api 调用引入数据,并使用 main.js 文件中的变量将数据输出到模板字符串内的 html。所有这些都运行良好。让我受阻的问题是我想要一个添加到收藏夹按钮,用户可以单击该按钮并将标题添加到收藏夹列表。当我在模板文字中添加按钮时,按钮的 addEvenListener 为 null,如果我将按钮添加到 index.html,我将无法从 api 访问数据。我试图在用户单击按钮后首先将数据存储到 firestore 数据库中。然后将数据输出到下拉列表中。

我已经在firestore数据库中添加了一个集合,可以将后端的数据显示到收藏夹列表中,但是我需要从前端抓取数据,将其存储在后端,然后将其显示在收藏夹中列表。

 function getMovie(){
    let movieId = sessionStorage.getItem('movieId');
    // Make a request for a user with a given ID
    axios.get("https://api.themoviedb.org/3/movie/" + movieId + "? 
    api_key=redacted")
   .then(function (response) {
     console.log(response)
     let movie = response.data;
    //console.log(movie);
    let output = `
      <div class="dropdown">
        <button class="dropbtn" id="dropbtn">Favorites</button>
        <div id="myDropDown" class="dropdown-content"></div>
      </div>
  `;
  $('#movie').html(output);
  })
  .catch(function (error) {
    console.log(error);
  });     
}

addFavorite.addEventListener('submit', (e) => {
e.preventDefault();

firebase.firestore().collection('favorites').add({
   Title: addFavorite['movieid'].value

}).then(() => {
    //close 
    console.log(addFavorite)
})    
})

不确定我是否需要为此功能进行另一个 API 调用。我做了一个 API 调用来获取电影列表,然后又调用了另一个 API 来获取一部电影。当用户转到我想要添加收藏夹按钮的一部电影时。我希望有人知道如何引导我走向正确的方向。第一次在 Stackoverflow 上提问,别伤害我,哈哈

最佳答案

我以简单的 ul 列表为例

<ul id="movie">
</ul>


<script>
    // DUMMY records
    const apiCallDataExample = [
        {
            id: 1,
            name: "A"
        },
        {
            id: 2,
            name: "B"
        },
        {
            id: 3,
            name: "C"
        }
    ];

    let movies = [];

    getMovie();

    function getMovie() {
        movies = apiCallDataExample; // You will call your API to get the data, and store it in upper scope 'movies' variable.
        let htmlContent = ''; // prepare your html content -> in your case it is droup down i guess.
        for (let movie of movies) {
            htmlContent += `
                <li>
                    <span> ${movie.name} </span>
                    <button onclick="addToFavourite(${movie.id})"> click me </button>
                </li>
            `

            // Attach click event or any listener to get selected movie id or any identifier
        }
        let elem = document.getElementById("movie").innerHTML = htmlContent;
    }


    /**
    *  click event will trigger and we can fetch selected movie by given identifier, in my case it is `id `field.
    */

    function addToFavourite(id) {
        let selected_movie = movies.find(movie => movie.id === id); // find your movie by id.
        console.log("selected movie is", selected_movie)
        // add your data into collection as per your defined property , my case { id, name}.

        /*

        // Your fire base function

        firebase.firestore().collection('favorites').add({
            id: selected_movie.id,
            name: selected_movie.name
        }).then(() => { })
        */
    }
</script>

关于javascript - 如何使用 vanilla javascript 将 api 调用的数据存储到 firestore 数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57319647/

相关文章:

ios - 在 Xcode 版本 11.5 (11E608c) 中为 Release模式构建时找不到“FirebaseCore/FirebaseCore.h”文件

javascript - 在 firebase firestore 上实时停止查询

javascript - Rails turbolinks JS 文件 Bug

javascript - Mvc完成异步脚本加载

javascript - 以特定方式分割字符串 JavaScript

firebase - 如何在 Firestore 中存储有关集合的元数据?

javascript - 如何完成类似 Google Keep 布局的操作

javascript - Google 数据层数据未传递到标签管理器助手

javascript - 带有 Firebase 数据的 Angular 应用程序 : why am I seeing data from the previous page?

node.js - 在 ES6 中导入 DocumentReference