【问题标题】:Cannot find a differ supporting object. NgFor only supports binding to Iterables such as Arrays找不到不同的支持对象。 NgFor 仅支持绑定到 Iterables,例如 Arrays
【发布时间】:2019-09-08 18:07:45
【问题描述】:

我无意中更改了某处的一些代码,现在我的帖子不再被拉出,有人能发现错误吗?

服务:

  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.

【问题讨论】:

  • 试试*ngFor="let post of posts | async"
  • 谢谢,但现在我明白了。 InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'
  • 你能显示来自this.db.collection('/posts') as AngularFirestoreCollection&lt;any[]&gt;的回复吗?
  • 根据以下答案中的 OP 问题和 cmets,确定他得到的是对象而不是数组。这就是您收到ngfor only supports binding to iterables 的原因。检查服务调用的响应和posts的内容以解决问题

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


【解决方案1】:

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

  1. AngularFirestoreCollection 应该传递集合的项目类型,这里是数组类型 (any[]),但像 Post 这样的更合适。
  2. 您必须在您的收藏上调用valueChanges()snapshotChanges() 以获得可观察到的信息。 this.db.collection('/posts') 只返回对集合的引用(管理它的对象),而不是列表本身。
  3. 然后使用模板中的 async 管道自动订阅/取消订阅返回的 observable。

为您服务:

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>

【讨论】:

  • @FullerPrime,这是表示 Observable 的约定
猜你喜欢
  • 2020-08-29
  • 1970-01-01
  • 2021-01-12
  • 2018-07-14
  • 2017-02-10
  • 1970-01-01
  • 1970-01-01
  • 2018-01-01
相关资源
最近更新 更多