javascript - 从 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"
}
}
}
解决方案
推荐阅读
- java - 解组 - 内部(子)元素为空
- node.js - 当 Apollo Server 处于生产模式时,如何借助 graphql-codegen 为 React 生成 Graphql 类型?
- r - 绘制 GAM 模型的输出
- r - RSelenium - 如何滚动加载分隔线内的内容
- amazon-web-services - AWS 将策略设置为特定的 S3 存储桶文件夹
- android - SwitchCompat onClick 未从 XML 布局触发
- python - 读取多个 url 在 Python 中不起作用
- javascript - 如何从对象内部删除项目
- python - 运行 else 循环一次
- python - 如何从 C 扩展定义 Python 元类?