找不到不同的支持对象。 NgFor 仅支持绑定到 Iterables,例如 Arrays

Cannot find a differ supporting object. NgFor only supports binding to Iterables such as Arrays

我不小心更改了某处的一些代码,现在我的帖子不再被提取,有人能发现错误吗?

服务:

  posts: AngularFirestoreCollection<any[]>;

  constructor(private db: AngularFirestore) { }

  getPosts() {
    this.posts = this.db.collection('/posts') as AngularFirestoreCollection<any[]>;
    return this.posts;
  }
}

Post 分量:


  posts: AngularFirestoreCollection<any>;

  constructor(private firebaseService: FirebaseService) { }

  ngOnInit() {
    this.posts = this.firebaseService.getPosts();
  }

}

Post 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. AngularFirestoreCollection 应该传递你的 collection 的项目类型,在这里你是一个数组类型 (any[]),但像 Post 这样的东西会更合适。
  2. 您必须在 collection 上调用 valueChanges()snapshotChanges() 才能对其进行观察。 this.db.collection('/posts') 只是 returns 对 collection 的引用(一个 object 来管理它)而不是列表本身。
  3. 然后使用模板中的 async 管道从返回的 observable 中自动 subscribe/unsubscribe。

为您服务:

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>