【问题标题】:AngularFire2 retrieve Object data not working, but List data doesAngularFire2 检索对象数据不起作用,但列表数据起作用
【发布时间】:2017-11-14 07:33:03
【问题描述】:

我正在尝试使用 Typescript 中的 AngularFire2 从 Firebase 读取数据。我的代码在检索数据列表时使用异步管道,但在获取对象时,我无法访问内容。

Firebase 上的数据结构:(myapp.firebaseio.com/LeagueStandings)

代码子集:

import { Component } from '@angular/core';
import { AngularFireDatabase, FirebaseObjectObservable } from 'angularfire2/database';

Standings: FirebaseObjectObservable<any[]>;
constructor(public FirebaseData:AngularFireDatabase) {
    this.Standings = FirebaseData.object('/LeagueStandings');
    // Added the following to see the debug
    this.Standings.subscribe(data => { 
        console.log(data); 
    });
}

HTML 示例位:

<ion-col><ion-badge color="secondary">{{Standings.Wins | async }}</ion-badge></ion-col>

问题是数据永远不会显示。但是,使用 FirebaseData.list 对数组数据(例如个人游戏统计数据)进行同样的处理确实有效。我不知道如何轻松提取要显示的页面的数据结构。

添加控制台转储确实会显示从 Firebase 返回的数据,但我的 home.html 没有更新。

【问题讨论】:

  • 你在哪里设置LeagueInfo
  • 对不起,这是一个从编辑代码到小样本复制过来的错字。我已经更新了 HTML,因为它应该引用排名。
  • 我还在调查它,但你是否尝试过其他语法?像那样`排名['Wins']`? (远射.. :))
  • 试过了,没有额外的运气。

标签: firebase firebase-realtime-database angularfire2 typescript2.0


【解决方案1】:

显然仔细阅读AngularFire2 documentation 将解决问题。我注意到文档是如何显示数据的,并更改了我的代码以匹配,并且它有效。我只需要更改 HTML。

import { Component } from '@angular/core';
import { AngularFireDatabase, FirebaseObjectObservable } from 'angularfire2/database';

Standings: FirebaseObjectObservable<any[]>;
constructor(public FirebaseData:AngularFireDatabase) {
    this.Standings = FirebaseData.object('/LeagueStandings');
}

HTML 示例位:

<ion-col><ion-badge color="secondary">{{Standings.Wins | async }}</ion-badge></ion-col>

更改为:

<ion-col><ion-badge color="secondary">{{ (Standings | async)?.Wins }}</ion-badge></ion-col>

(Standings | async)?.Wins 是更正。使用异步管道等待对象,然后是可选字段 (?),然后是字段 (.Wins)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 2016-10-23
    • 1970-01-01
    相关资源
    最近更新 更多