我正在尝试将Angular5与Firestore一起使用的示例,但我无法从Firestore数据库中检索任何数据。任何帮助将不胜感激,因为这是一个显示塞子。具有讽刺意味的是,我可以使用示例将新记录插入数据库,我只是无法检索任何内容。提前致谢。
app.component.html:
<ul *ngFor="let post of posts | async">
<li>
<strong>{{ post.title }}</strong>
<br>
{{ post.content }}
</li>
</ul>
app.component.ts:
import { Component } from '@angular/core';
import { AngularFirestore } from 'angularfire2/firestore';
import { AngularFirestoreCollection } from 'angularfire2/firestore';
import { AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
interface Post {
title: string;
content: string;
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
postsCollection: AngularFirestoreCollection<Post>;
posts: Observable<Post[]>;
constructor (private afs: AngularFirestore) {
}
ngOnit() {
this.postsCollection = this.afs.collection('posts');
this.posts = this.postsCollection.valueChanges();
}
}
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AngularFireModule } from 'angularfire2';
import { AngularFirestoreModule } from 'angularfire2/firestore';
import { FormsModule } from '@angular/forms';
var firebaseConfig = {
apiKey: "edited but correct",
authDomain: "edited but correct",
databaseURL: "edited but correct",
projectId: "edited but correct",
storageBucket: "",
messagingSenderId: "edited but correct"
};
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AngularFireModule.initializeApp(firebaseConfig),
AngularFirestoreModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
看起来像一个错字:
ngOnit() {
应该:
ngOnInit() {}
(如果它还没有准备好在生命周期中的那一点加载,你甚至可能需要ngAfterContentInit()。)
错误就在这一行
ngOnInit() {
this.postsCollection = this.afs.collection('posts'); <<HERE
this.posts = this.postsCollection.valueChanges();
}
将其更改为:
this.postCollection = this.afs.collection< post > ('posts')
供参考,您可以阅读本页:
https://blog.angular.io/improved-querying-and-offline-data-with-angularfirestore-dab8e20a4a06