【问题标题】:fetch data from firebase in angular 5以角度 5 从 firebase 获取数据
【发布时间】:2018-11-06 18:05:12
【问题描述】:

我是 firebase 和 angular 的新手,一步步尝试学习我在 firebase 中创建的数据,现在想进入 angular 5。但它不起作用。

Firebase 数据结构:

category.service.ts:

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class CategoryService {

  constructor(private db: AngularFireDatabase) { }

  getCategories(){
    return this.db.list('/categories').valueChanges();
  }

}

Product-form.component.ts

import { CategoryService } from './../../category.service';
import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-product-form',
  templateUrl: './product-form.component.html',
  styleUrls: ['./product-form.component.css']
})
export class ProductFormComponent implements OnInit {
  categories$; // Observable

  constructor(private categoryService: CategoryService) {
  }

  ngOnInit() {
    this.categories$ = this.categoryService.getCategories();
    console.log(this.categories$);
  }

}

product-form.component.html

<select class="form-control" name="" id="category">
        <option value=""></option>
        <option  *ngFor="let c of categories$ | async" [value]="c.$key">
          {{c.name}}
        </option>
    </select>

我得到的控制台错误:

请告诉我我的代码有什么问题。

【问题讨论】:

  • 可以添加整个错误日志吗?
  • console.log(this.categories$)说什么?
  • Observable {_isScalar: false, source: Observable, operator: MapOperator} operator : MapOperator project : ƒ (actions) thisArg : undefined proto : Object source : Observable _isScalar : false _subscribe : ƒ (subscriber) proto : Object _isScalar : false proto : Object
  • 嗨,你有没有解决你的问题..

标签: angular firebase angular5


【解决方案1】:

你在使用 rxjs 吗?也许考虑查看我已经回答过类似问题的这个线程。 RXJS-version problem

在大多数情况下,问题在于您的 rxjs 版本不在版本 6 上。另外请考虑您是否使用低于 6 的版本并尝试升级查看我的答案。迁移到版本 6 时应遵循迁移指南。

希望这能解决您的问题。

【讨论】:

  • 是的,我使用的是 rxjs 5.5.6 和 angular 5。要升级 rxjs,我必须更新我不想要的 angular 5。
  • 您使用的是哪个角火版本?从 5. 开始的版本需要 rxjs 6.
  • 谢谢@Benjamin....它现在可以工作了..而不是升级rxjs,我降级了angularfire。
  • 是的,这是一种可能性,但请考虑到许多 angularfire2 功能,如 credentialLess 身份验证等,都是高版本的一部分。如果这对您来说没有问题,请保持这种状态。否则,您可能需要考虑升级而不是降级。
【解决方案2】:

您应该尝试使用for in 循环。订阅httpobservable,然后使用for in 循环将其填充到您的业务逻辑所需的数组或数据结构中。

然后在 HTML 中使用这个新的数据结构。如果你选择一个数组,for of 循环肯定会在你的 HTML 文件中工作。

希望对您有所帮助。祝你好运!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    • 2018-09-29
    • 2021-03-02
    相关资源
    最近更新 更多