typescript Angular 4 Firebase 从数据库读取数据并显示到浏览器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45242925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 4 Firebase Read data from database and display to browser
提问by Vasilis Michail
I am learning Angular 4 and I am using firebase database.But I am completly lost on how I can make the objects apear on the browser of my application. I currently want to take all the data from users and display them on the browser.
我正在学习 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() {
}
}
Everything works fine and I can see my data on the console.But can you help me on how I can make the data on the console apear on the browser??
一切正常,我可以在控制台上看到我的数据。但是你能帮助我如何使控制台上的数据显示在浏览器上吗?
采纳答案by Vasilis Michail
Well there is no need to use console.log() if you want to display data on Browser.Angularfire has its own functions for this. This link focus exactly on your problem
好吧,如果您想在 Browser.Angularfire 上显示数据,则无需使用 console.log() 对此有自己的功能。 此链接完全关注您的问题
Here is an example that takes all the users name from a database and displays them as a list
这是一个从数据库中获取所有用户名并将它们显示为列表的示例
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() {
}
And the following Html code
以及以下 Html 代码
<div class="container">
<p>Show all users</p>
<ul>
<li *ngFor="let user of users | async">
{{ user.name | json }}
</li>
</ul>
</div>
Hope it reduced your confusion on the matter.If you didnt understant something plz ask me again
希望它减少了您对此事的困惑。如果您没有理解某些事情,请再问我一次