xRuhRohx
xRuhRohx

Reputation: 422

How do I get data using firebase with angularfire2 version 5?

I have been following a few guides on the update process from angularfire2 v4 to v5, to no avail. I cannot seem to get the data where it needs to go. I can get the data from firebase and display it in the console, but for some reason I cannot get it to show up in my ngFor loop. There is one way I am able to get it to show up but I also get an error so I am certain it is wrong.

I have also tried setting up my code exactly as it is here and nothing. https://alligator.io/angular/cloud-firestore-angularfire/

The error I get is

error TS2322: Type '{}[]' is not assignable to type 'Chat[]'

Onward to my code.

chat.service.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { Chat } from './../models/chat';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/take';

@Injectable()
export class ChatService {

  constructor(
    private db: AngularFireDatabase
  ) { }

  getAll() {
    return this.db.list('/chats');
  }

chat-list.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from './../../../admin/services/auth.service';
import { Observable } from 'rxjs/Observable';
import { AppUser } from './../../models/app-user';
import { ChatService } from './../../services/chat.service';
import { Chat } from './../../models/chat';
import * as firebase from 'firebase';

@Component({
  selector: 'chat-list',
  templateUrl: './chat-list.component.html',
  styleUrls: ['./chat-list.component.css']
})
export class ChatListComponent implements OnInit {
  appUser: AppUser;
  chats: Chat[] = [];

  constructor(
    private auth: AuthService,
    private chatService: ChatService
  ) {
    auth.appUser$.subscribe(appUser => this.appUser = appUser);

// This is where the error is showing up --------------|__ERROR__|
    chatService.getAll().valueChanges().subscribe(c => this.chats = c);
  }

  async ngOnInit() {
  }
}

chat-list.component.html

<li *ngFor="let c of chats" class="list-group-item">
   {{ c.name }}
</li>

Upvotes: 0

Views: 732

Answers (1)

ibenjelloun
ibenjelloun

Reputation: 7733

Try using this.db.list<Chat>('/chats').valueChanges();.

I put return types when i can to help detect errors in compilation, it would help to put a return type in your service.

getAll(): Observable<Chat[]> {
    return this.db.list<Chat>('/chats').valueChanges();
}

Upvotes: 1

Related Questions