【问题标题】:Type 'Observable<DocumentData[]>' is not assignable类型 'Observable<DocumentData[]>' 不可分配
【发布时间】:2022-01-27 00:18:18
【问题描述】:

我是 angular 和 firebase 的新手,我尝试使用 angular/fire 库的示例做一个简单的程序:

import { Component } from '@angular/core';
import { Firestore, collectionData, collection } from '@angular/fire/firestore';
import { Observable } from 'rxjs';

interface Item {
  name: string
};

@Component({
  selector: 'app-root',
  template: `
  <ul>
    <li *ngFor="let item of item$ | async">
      {{ item.name }}
    </li>
  </ul>
  `
})
export class AppComponent {
  title = 'firetest2812';
  item$: Observable<Item[]>;
  constructor(firestore: Firestore) {
    const collect = collection(firestore, 'items');
    this.item$ = collectionData(collect);
  }
}

编译时出现以下错误:“错误:src/app/app.component.ts:24:5 - 错误 TS2322:类型 'Observable' 不可分配给类型 'Observable'。”

谁能告诉我怎么了? 谢谢!

【问题讨论】:

    标签: angular typescript firebase


    【解决方案1】:

    您需要在collectionData() 函数中提供泛型类型,因为您在属性中将item$ Observable 类型指定为Item[]

    export class AppComponent {
      title = 'firetest2812';
      item$: Observable<Item[]>;
      constructor(firestore: Firestore) {
        const collect = collection(firestore, 'items');
        // Specify the type here
        this.item$ = collectionData<Item>(collect);
      }
    }
    

    或者,懒惰的答案是使用any

    export class AppComponent {
      title = 'firetest2812';
      item$: Observable<any[]>;
      constructor(firestore: Firestore) {
        const collect = collection(firestore, 'items');
        // Specify the type here
        this.item$ = collectionData(collect);
      }
    }
    

    【讨论】:

      【解决方案2】:

      您必须将您的接口作为类型传递给collection 函数。

       const collect = collection<Item>(firestore, 'items');
      

      【讨论】:

      • 谢谢,但它不起作用“ 预期 0 类型参数,但得到 1. 24 const collect = collection(firestore, 'items'); "
      • 您可以尝试在 collectionData 上提供类型吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-19
      • 2020-11-23
      • 2019-01-12
      • 2018-08-14
      • 2021-01-02
      • 2016-09-10
      • 2018-03-09
      相关资源
      最近更新 更多