从Firebase数据库Angle 8读取数据

时间:2019-09-14 21:42:21

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

我正在尝试从Firebase数据库读取数据,这是我的代码: 我的组件:

import { Component, OnInit } from '@angular/core';
import { ProductService } from 'src/app/services/product.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-admin-products',
  templateUrl: './admin-products.component.html',
  styleUrls: ['./admin-products.component.css']
})
export class AdminProductsComponent implements OnInit {
  products$:Observable<any>;
  constructor(private productService: ProductService) {

    //Just try to log what the db will give me back

    this.productService.getProducts().subscribe(re=>console.log(re));
  }

  ngOnInit() {
    this.products$=this.productService.getProducts();
  }

}

这是我的ProductService:

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';

@Injectable({
  providedIn: 'root'
})
export class ProductService {
  constructor(private db: AngularFireDatabase) { }

  postProduct(formValue) {
    this.db.list('/products').push(formValue);
  }

  getProducts(){
    return  this.db.list('/products').snapshotChanges(); 
  }
}

我在控制台中得到以下结果: result in the console

,我的数据库如下: my database, only the products node is used in this code

我从数据库中需要的是键和值(使用valuechanges()而不是snapshotchanges()仅提供不包含键的值),我得到的结果是一团糟,请问您如何从中读取数据库在firebase中?

"dependencies": {
    "@angular/animations": "~8.2.3",
    "@angular/common": "~8.2.3",
    "@angular/compiler": "~8.2.3",
    "@angular/core": "~8.2.3",
    "@angular/fire": "^5.2.1",
    "@angular/forms": "~8.2.3",
    "@angular/platform-browser": "~8.2.3",
    "@angular/platform-browser-dynamic": "~8.2.3",
    "@angular/router": "~8.2.3",
    "@ng-bootstrap/ng-bootstrap": "^5.1.1",
    "bootstrap": "^4.3.1",
    "firebase": "^6.6.0",
    "rxjs": "~6.4.0",
    "tslib": "^1.10.0",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.803.0",
    "@angular/cli": "~8.3.0",
    "@angular/compiler-cli": "~8.2.3",
    "@angular/language-service": "~8.2.3",
    "@types/node": "~8.9.4",
    "ts-node": "~7.0.0",
    "typescript": "~3.5.3"
  }

1 个答案:

答案 0 :(得分:2)

snapshotChanges获取密钥和有效负载的方法是将payload.val()用于有效负载,将payload.key用于密钥:

return this.db.list('/products').snapshotChanges().pipe(
  map((products: any[]) => products.map(prod => {
    const payload = prod.payload.val();
    const key = prod.key;
    return <any>{ key, ...payload };
  })),
);

请不要使用any,TypeScript,顾名思义,其主要用途是强类型数据。它会极大地帮助您开始键入数据,因为IDE会在您尝试执行错误操作时告诉您。在上面我使用了any,因为您还没有输入数据。但是不要这样做! ;)