找不到其他支持对象。 NgFor仅支持绑定到可迭代对象,例如数组

时间:2019-04-18 11:49:38

标签: angular typescript firebase google-cloud-firestore angularfire2

我无意间更改了某些代码,现在我的帖子不再被删除,有人可以发现错误吗?

服务:

  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.

1 个答案:

答案 0 :(得分:2)

以下是一些解决您问题的建议:

  1. AngularFirestoreCollection应该传递集合的项目类型,这里是数组类型(any[]),但是像Post这样的东西更合适。
  2. 您必须调用集合中的valueChanges()snapshotChanges()才能对其进行观察。 this.db.collection('/posts')仅返回对集合的引用(用于管理集合的对象),而不返回列表本身。
  3. 然后使用模板中的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>