Search code examples
angulartypescriptfirebasegoogle-cloud-firestoreangularfire

Assign a documents values as a <Type>


Making an Observable <Hero[]> out of a collection works perfectly and gives me access to all its documents, but I am unable to assign individual documents. The recurring error message is the following:

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

The working code for collections:

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;

Then I use this return in other components:

heroes : Hero[]=[];

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

But when it comes to documents:

  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;
  }     

I receive this error message:

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

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


Solution

  • The solution was a subscription to the document instance:

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