Home > Mobile >  Object is of type "unknown" error trying to display data from a Firebase database
Object is of type "unknown" error trying to display data from a Firebase database

Time:07-22

I'm following a tutorial for reading and displaying data from a Firebase database, but it seems like the tutorial may be a bit out of date because I am getting an error when I try to display the data in the app.component.html template.

I have a simple database setup that has an "authors" record with some data about an author.

In the app.component.ts file I define an observable field based on this object.

import { Component } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/compat/database';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  author$;

  constructor(db: AngularFireDatabase) {
    this.author$ = db.object('/authors/1').valueChanges();
  }
}

And then I try to display this data in app.component.html.

<ul *ngIf="author$ | async as author">
  <li>{{ author.name }}</li>
  <li>{{ author.students }}</li>
  <li>{{ author.isPremium }}</li>
</ul>

In the tutorial it just works without problems, but when I try to do this I get an error on each of these three attributes. enter image description here

I'm still fairly new to Angular and TypeScript in general so I'm not sure how to resolve the problem. I tried Googling for a solution but everything that came up seemed unrelated to this particular problem. Can someone explain why I am getting this error and how to resolve it?

CodePudding user response:

I was able to make it work by declaring author$ as a type of Observable<any> although I feel like using any generally defeats the purpose of TypeScript.

export class AppComponent {
  author$: Observable<any>; // <--- changed this line

  constructor(db: AngularFireDatabase) {
    this.author$ = db.object('/authors/1').valueChanges();
  }
}

Since this does work I am posting it as a solution, but if there is a better solution please let me know.

  • Related