首页 > 解决方案 > 从 firebase 实时数据库中获取 JSON 数据

问题描述

在我的最后一个问题导致死胡同之后,我现在尝试从实时数据库中以 JSON 格式获取数据(通常只需将“.json”添加到数据链接的末尾即可完成)

但是当我尝试序列化数据时,它不会创建 JSON 并说 .length 无法读取 undefined 即使在控制台中数据在那里。

这是我从 fetch() 得到的:

Output:  {-MHqJuAp0XT1Ko780Cdx: {…}, -MHqfacixCOJeI_JSr__: {…}}

index.js?4360:36 OutputLenght:  undefined

index.js?4360:47 {-MHqJuAp0XT1Ko780Cdx: {…}, -MHqfacixCOJeI_JSr__: {…}}

index.js?4360:51 Uncaught (in promise) TypeError: myJson.slice is not a function
    at _callee2$ (index.js?4360:51)
    at tryCatch (runtime.js?96cf:63)
    at Generator.invoke [as _invoke] (runtime.js?96cf:293)
    at Generator.eval [as next] (runtime.js?96cf:118)
    at asyncGeneratorStep (asyncToGenerator.js?1da1:3)
    at _next (asyncToGenerator.js?1da1:25)

这是我的代码:

async fetchData(){
          
          const user = (await firebase.auth().currentUser);
          const fblink = await firebase.database().ref("events/public").toString()+".json?auth=" + (await user.getIdTokenResult()).token;

          return await fetch(fblink)
          .then(res => res.json())
          .then((out) => {
            
            console.log('Output: ', out);
            return(out);
          }).catch(err =>{ console.error(err); return null});
    },

    async fetchEvents({dispatch,commit},{perPage})
    {
      const myJson = await dispatch("fetchData");
      commit("SET_EVENTS", myJson);
      commit("SET_ROWS", myJson.length );

      const displayEvents = myJson.slice(0,perPage);
      commit("SET_DISPLAY_EVENTS",displayEvents);
      commit("SET_ROWS" , myJson.length);
    }

这是数据库中的数据:

{
  "public" : {
    "-MHqJuAp0XT1Ko780Cdx" : {
      "date" : "2020-09-09",
      "id" : 14,
      "img" : "https://cdn.discordapp.com/attachments/743104050744262797/748929414607405197/IMG_20200828_173755.jpg",
      "name" : "TEST",
      "shortDesc" : "herllo",
      "start" : "22:57:00"
    },
    "-MHqfacixCOJeI_JSr__" : {
      "date" : "2020-09-01",
      "id" : 1,
      "img" : "https://cdn.discordapp.com/attachments/743104050744262797/748929414607405197/IMG_20200828_173755.jpg",
      "name" : "asda",
      "shortDesc" : "dasdasda",
      "start" : "22:58:00"
    }
  }
}

标签: javascriptjsonfirebasefirebase-realtime-databasefetch

解决方案


推荐阅读