我无意间更改了某些代码,现在我的帖子不再被删除,有人可以发现错误吗?
服务:
posts: AngularFirestoreCollection<any[]>;
constructor(private db: AngularFirestore) { }
getPosts() {
this.posts = this.db.collection('/posts') as AngularFirestoreCollection<any[]>;
return this.posts;
}
}
发布组件:
posts: AngularFirestoreCollection<any>;
constructor(private firebaseService: FirebaseService) { }
ngOnInit() {
this.posts = this.firebaseService.getPosts();
}
}
发布HTML:
<mat-grid-tile *ngFor="let post of posts">
<mat-card class="mat-elevation-z4">
<img mat-card-image src="{{post.imgUrl}}">
<mat-card-actions>
<button mat-icon-button><mat-icon>thumb_up_alt</mat-icon></button><span class="counter mat-small">{{post.numberOfLikes}}</span>
<button mat-icon-button><mat-icon>star</mat-icon></button><span mat-small class="counter mat-small">{{post.numberOfSaves}}</span>
</mat-card-actions>
</mat-card>
</mat-grid-tile>
</mat-grid-list>``
现在我得到Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
答案 0 :(得分:2)
以下是一些解决您问题的建议:
AngularFirestoreCollection
应该传递集合的项目类型,这里是数组类型(any[]
),但是像Post
这样的东西更合适。valueChanges()
或snapshotChanges()
才能对其进行观察。 this.db.collection('/posts')
仅返回对集合的引用(用于管理集合的对象),而不返回列表本身。async
管道自动订阅/取消订阅返回的可观察对象。为您服务:
export interface Post {
imgUrl: string;
numberOfLikes: number;
numberOfSaves: number;
}
@Injectable()
export class FirebaseService {
postsRef: AngularFirestoreCollection<Post>;
constructor(private db: AngularFirestore) { }
getPosts() {
this.postsRef = this.db.collection('/posts') as AngularFirestoreCollection<Post>;
return this.postsRef.valueChanges();
}
}
在您的组件中:
import { Observable } from 'rxjs';
import { FirebaseService, Post } from '....';
@Component({ ... })
export class MyComponent implements OnInit {
posts$: Observable<Post[]>;
constructor(private firebaseService: FirebaseService) { }
ngOnInit() {
this.posts$ = this.firebaseService.getPosts();
}
}
在您的模板中:
<mat-grid-tile *ngFor="let post of posts$ | async">
...
</mat-grid-list>