Angular 4 Firebase从数据库读取数据并显示到浏览器

时间:2017-07-21 16:55:02

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

我正在学习Angular 4,我正在使用firebase数据库。但是我完全不知道如何在我的应用程序的浏览器上创建对象。 我目前想要从用户那里获取所有数据并在浏览器上显示它们。

import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
import * as firebase from 'firebase/app';

@Component({
  selector: 'app-about',
  templateUrl: './about.component.html',
  styleUrls: ['./about.component.css']
})
export class AboutComponent implements OnInit {

  constructor() {
    var allUsers = firebase.database().ref('users/');
      var db = firebase.database().ref('/users/');
      // Attach an asynchronous callback to read the data at our posts reference
        db.on("value", function(snapshot) {
          console.log(snapshot.val());
        }, function (errorObject) {
          console.log("The read failed: " + errorObject.code);
        });
          }

  ngOnInit() {
  }

}

一切正常,我可以在控制台上看到我的数据。但是,你可以帮助我如何在浏览器上创建控制台数据吗?

1 个答案:

答案 0 :(得分:3)

如果你想在Browser.Angularfire上显示数据,就没有必要使用console.log()。它有自己的功能。 This link focus exactly on your problem

这是一个从数据库中获取所有用户名并将其显示为列表

的示例
import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable,FirebaseObjectObservable } from 'angularfire2/database';
import * as firebase from 'firebase/app';

@Component({
  selector: 'app-about',
  templateUrl: './about.component.html',
  styleUrls: ['./about.component.css']
})
export class AboutComponent implements OnInit {

    users:FirebaseListObservable<any>;;
    constructor(db2: AngularFireDatabase) {
    this.users = db2.list('users');
          }
  ngOnInit() {
  }

以下Html代码

<div class="container">
  <p>Show all users</p>
  <ul>
  <li *ngFor="let user of users | async">
       {{ user.name | json }}
    </li>
  </ul>
</div>

希望它能减少你对此事的困惑。如果你没有理解某事,请再次问我