【问题标题】:how do I get a single value from firebase using angularfire2 and angular5?如何使用 angularfire2 和 angular5 从 firebase 获取单个值?
【发布时间】:2017-11-19 17:34:00
【问题描述】:

我正在尝试从 firebase 获取并显示单个值。

我的 firebase 结构如下所示:

我当前的 .ts 文件如下所示:

storestat$: Observable<any[]>;

constructor(afDb: AngularFireDatabase) {
     this.storestat$ = afDb.list<any>('MyShop').snapshotChanges();
}

我想使用 {{}} 绑定在 html 中显示 storeStatus 值。类似于以下内容:

<button>{{ storeStatus }} Status</button>

我最初尝试使用以下内容:

<ng-container *ngFor="let s of storestat$ | async">...
<button>{{ s.storeStatus }}</button>

但这当然行不通。

我尝试搜索答案,但它们似乎不太相关,因为它们都指向从列表中获取多个特定值。

我正在使用 angularfire2 和 angular5。

我是 angular5 的新手,因此我们将不胜感激,包括任何教育指针。

【问题讨论】:

  • 调试尝试&lt;p&gt;{{ s | json }}&lt;/p&gt; 并检查数据是否到来?
  • 我收到以下错误:AppComponent.html:4 ERROR TypeError: Converting circular structure to JSON at JSON.stringify () at JsonPipe.transform (common.js:5954) at Object. eval [as updateDirectives] (AppComponent.html:4) at Object.debugUpdateDirectives [as updateDirectives] (core.js:14339) at checkAndUpdateView (core.js:13508) at callViewAction (core.js:13858) at execComponentViewsAction (core. js:13790)...
  • 试试.valueChanges()方法。
  • 这也给出了同样的错误。我在下面发布了一个解决方案,但我认为它有点混乱。

标签: angular firebase firebase-realtime-database angularfire2 angular5


【解决方案1】:

我有一个解决方法,但不确定它是否是最佳解决方案。我的新 .ts 文件相关部分如下所示:

    this.storestat$ = afDb.list<any>('myshop').snapshotChanges()
       .map(
            changes => {
               return changes.map(
                  c => ({ val: c.payload.val(), 
                          key: c.payload.key,
                          ...c.payload.val()
                   })
               );
       });

我的 .html 相关部分现在看起来像:

<ng-container *ngFor="let s of storestat$ | async">

  <button *ngIf="s.key == 'storeStatus'">{{ s.val }} Status</button>

</ng-container>

我认为这不是最干净的解决方案,因为数据库调用也映射了不需要的 Current Orders 分支,但它确实有效。

【讨论】:

    【解决方案2】:

    如果你不关心按键,你可以使用.valueChanges(),它应该像这样工作

    afDb.list<any>('myshop').valueChanges().subscribe(value => 
    {
        this.storestat$ = value;
    });
    

    在html中

    <ng-container *ngFor="let s of storestat$">
    
      <button>{{ s.storeStatus }} Status</button>
    
    </ng-container>
    

    【讨论】:

    • 我认为这会起作用,但事实并非如此。无论出于何种原因,storeStatus 的值都没有按应有的方式传递。这就是为什么我必须在下面的解决方案中明确映射值。
    • 你能展示一下myshop的完整结构吗?仅显示在您的图像中的一部分
    • 我已经修改了我原来的帖子以显示myshop的完整结构
    • storeStatusCurrentOrders 下吗?
    • 我不知道为什么它不起作用。我用订阅改变了我的答案。用异步管道试试这个。
    猜你喜欢
    • 1970-01-01
    • 2019-11-07
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 2018-04-30
    • 1970-01-01
    • 2016-11-12
    • 2017-01-18
    相关资源
    最近更新 更多