在 Ionic 2 中从 Firebase 获取数据 [英] Get data from Firebase in Ionic 2

查看:23
本文介绍了在 Ionic 2 中从 Firebase 获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 ionic 2 编写了我的应用程序,并遵循了 Josh Morony 教程,但我不知道如何从我的 firebase 数据库中获取特定元素.

I have written my app with ionic 2 and followed the tutorial of Josh Morony, but I don't know how I can get a specific element from my firebase database.

例如我有这棵树:

user

|__ (user_id)

  |_ name : 'toto'

等等……

我试过这样:

elt: FirebaseListObservable<any[]>;
this.elt = af.database.list('/user');

但是我如何处理选定的数据?

But how can I work with the selected data?

推荐答案

为了从提供者处以数组的形式获取数据,您需要返回一个承诺,该承诺将在 firebaseListObservable 事件发生后返回由返回数据触发.

In order to get the data as an array from a provider you need to return a promise which will be returned once the firebaseListObservable event is triggered with return data.

在你的提供者 .ts

getData(fbPath): Promise<any> {
  return new Promise(resolve => {
    this.db.list(fbPath).subscribe(data => {
      resolve(data);
    })
  })
}

这里,一旦 data 被填充,promise 就会解析,并返回一个可以轻松访问 $value$key 属性的数组.这是创建条件或复杂查询或具有通用属性的提供程序服务的理想选择(而不是直接查询 firebaseListObservable 的快照)

Here the promise resolves once the data is populated and returns an array with easy access to the $value and $key properties. Which is ideal for creating conditionals or complex queries or a provider service with generic properties ( as opposed to querying the snapshot of the firebaseListObservable directly )

在你的控制器中你可以写一些类似的东西

In your controller you can then write something like

 this.providerName.getData('users').then(data => {
    console.log('data',data);
  })

这将返回一个带有值的对象字面量

This will return an object literal with the values

  • $ 存在
  • $key
  • $value

所以现在如果你想要一个匹配条件,你可以循环遍历 data 和表 users$key 上的匹配条件

So now if you want a match conditional you can loop through the data with the match condition on the $key of the table users

if(myUserIdVar === data.$key){ // do something here };

使用诸如 lodash 之类的库可以找到更简洁的语法.例如,如果您愿意匹配存储的 id 的条件,比如 firebase.auth().currentUser.uid 你可以做一个简单的 _.find

A tidier syntax can be found using a library like lodash Where for example if you want a condition to match a stored id, say firebase.auth().currentUser.uid you can do a simple _.find

 import { find } from 'lodash';
 import * as firebase from 'firebase'; // Or just the firebase auth stuff
 ...

 let filteredUser = find(data, ['$key', firebase.auth().currentUser.uid])

$key 值将等于 |__ (user_id)

这篇关于在 Ionic 2 中从 Firebase 获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆