将文档值分配为 <Type>

Assign a documents values as a <Type>

从集合中创建一个 Observable 效果很好,让我可以访问它的所有文档,但我无法分配单个文档。重复出现的错误消息如下:

Type 'Hero | undefined' is not assignable to type 'Hero'.

集合的工作代码:

export class DataManagerService {

    heroesCollection : AngularFirestoreCollection<Hero>;
    heroesData:Observable<Hero[]>;
.
.
constructor(private firestore:Firestore){

    this.heroesCollection = this.firestore.collection<Hero>('HEROES');
    this.heroesData = this.heroesCollection.valueChanges();  
.
.
getHeroes():Observable<Hero[]>{

    return this.heroesData;

然后我在其他组件中使用这个return:

heroes : Hero[]=[];

  getHeroes():void{
    this.DataManagerService.getHeroes().subscribe(heroes =>this.heroes=heroes);
  }

但是在文件方面:

  heroDocument : AngularFirestoreDocument<Hero>;
  public heroData:Observable<Hero>;
  this.heroDocument = this.firestore.doc('Z8NylmZfeUIuQnmaz2cy');
  this.heroData = this.heroDocument.valueChanges();       
getHero(id:number):Observable<Hero>{ 
    return this.heroesData;
  }     

我收到此错误消息:

Type 'undefined' is not assignable to type 'Hero'. return

this.heroData= this.heroDocument.valueChanges();

解决方案是订阅文档实例:

this.itemDoc.valueChanges().subscribe(hero=>this.hero = heroData as Hero);