skip to Main Content
@Injectable({
  providedIn: 'root'
})
export class ChatService {

 
  config = {
    apiKey: "",
  authDomain: "",
  databaseURL: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: ""
  };

  app = initializeApp(this.config);
  database = getDatabase(this.app);
  messagesRef = ref(this.database, "messages");

  constructor() {}

  
  sendMessage(newMessage: string) {
    if (newMessage.trim()) {
      push(this.messagesRef, {
        text: newMessage,
        createdAt: new Date().toString()
      });
    }
  }

  
  getMessages(): Observable<any[]> {
    return new Observable((observer) => {
      onValue(this.messagesRef, (snapshot) => {
        const data = snapshot.val();
        const messages = data ? Object.values(data) : [];
        observer.next(messages);
      });
    });
  }
}

so I’m trying to implement a real-time database of firebase to my service typescript file but this error appears : Property ‘list’ does not exist on type ‘DatabaseReference’.
any solution ?
I tried to change the code but I got a similar error ( Property ‘list’ does not exist on type ‘Database’

2

Answers


  1. You’re configuring Firebase with its regular JavaScript SDK in your code, but then try to use the list() method which only exists in the AngularFire wrapper library.

    If you want to use the AngularFire API, initialize and inject it as shown in the AngularFire developers guide for Realtime Database. From there:

    As a prerequisite, ensure that AngularFire has been added to your project via

    ng add @angular/fire
    

    Provide a Database instance in the application’s app.config.ts:

    import { provideFirebaseApp, initializeApp } from '@angular/fire/app';
    import { provideDatabase, getDatabase } from '@angular/fire/database';
    
    export const appConfig: ApplicationConfig = {
      providers: [
        provideFirebaseApp(() => initializeApp({ ... })),
        provideDatabase(() => getDatabase()),
        ...
      ],
      ...
    })
    

    Next inject Database into your component:

    import { Component, inject } from '@angular/core';
    import { Database } from '@angular/fire/database';
    
    @Component({...})
    export class DepartmentComponent {
      private database = inject(Database);
      ...
    }
    

    You seem to have missed the first and the last part of that.

    Login or Signup to reply.
  2. The above answer (from @puf-FrankvanPuffelen) does resolve your error but doesn’t resolve your problem completely though.

    As mentioned in the answer earlier, you missed providing the Database instance in the application and injecting the database into your component/service.

    Only thing left is to get the DataSnapshot changes as an observable and subscribe to it

    Your Message Service

    import { Injectable, inject } from '@angular/core';
    import { Database, ref, listVal} from '@angular/fire/database';
    import { Observable } from 'rxjs';
    
    @Injectable({
      providedIn: 'root'
    })
    export class MessageService {
    
        db = inject(Database);
        messagesRef = ref(this.database, "messages");
        
        getMessages(): Observable<any[]> {
           return listValue(messagesRef)
        }
    }
    

    And subscribe to the observable in the component

    import { Component, inject, OnInit } from '@angular/core';
    import { MessageService } from '../../services/message.service';
    import { Subscription } from 'rxjs';
    ...
    
    export class MessageComponent implements OnInit, OnDestroy {
      messageService = inject(MessageService)
      sub!: Subscription
    
      ngOnInit(): void {
        this.sub = this.messageService.getMessages().subscribe(messages=> {
        console.log(messages)
      })
    
      ngOnDestroy(): void {
        this.sub.unsubscribe()
      }
    }
    ...
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search