我正在使用角度6,“ @ angular / fire”:“ ^ 5.1.1”,“ firebase”:“ ^ 5.6.0”,我想获取数据库中的所有数据,但没有得到它,我尝试了很多方法,这是我的appmodule.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AngularFireDatabaseModule } from '@angular/fire/database';
import {AngularFireModule} from '@angular/fire';
import {environment} from '../environments/environment';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
AngularFireDatabaseModule,
AngularFireModule.initializeApp(environment.firebase),
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
...这是我的appcomponent:
import { Component, OnInit} from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';
//import 'rxjs/add/operator/map';
import {Observable} from 'rxjs';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
courses: Observable<any[]>;
constructor(private db: AngularFireDatabase){
this.courses=db.list('/courses').snapshotChanges();
}
getData(){
return this.courses;
}
ngOnInit(){
console.log(this.getData());
debugger;
}
}
.... i也尝试过:
this.courses=db.list('/courses').valueChanges();
...和
this.courses=db.list('/courses').subscribe(courses=>{
this.courses=courses;
});
答案 0 :(得分:1)
snapshotChanges
返回一个可观察值。我们需要订阅可观察对象以获取数据。
constructor(private db: AngularFireDatabase){
db.list('/courses').snapshotChanges().subscribe((response) => {
this.courses= response;
});
}
答案 1 :(得分:1)
从文档中:
valueChanges(): The current state of your collection. Returns an Observable of data as a synchronized array of JSON objects. All Snapshot metadata is stripped and just the method provides only the data.
您应该订阅该函数返回的Observable,所以:
courses: Observable<CourseModel[]> | Observable<any> | any;
constructor(private db: AngularFireDatabase){
this.courses=db.list('/courses').valueChanges()
.subscribe(courses => {
console.log(courses); // Check the returned values;
this.courses = courses;
})
}