Reputation: 1167
I'm working on my first project using Angular and Firebase. Even thou everything works, I have a question about getting specific types of object. For example, I have a service that has a method called getAllNews()
, but I want this return to be a type News (created by me, there is a NewsModel file) but when I set the type, I get this from TSLint:
[ts]
Type 'Observable<{}[]>' is not assignable to type 'EventModel[]'.
Property 'length' is missing in type 'Observable<{}[]>
Can anybody shine a light here for me? Thank you so much!
Here is my code:
newsService.ts
import { Injectable } from '@angular/core';
import { AngularFireDatabase, AngularFireList } from '@angular/fire/database';
import { News } from '../news/news.model';
@Injectable({
providedIn: 'root'
})
export class NewsService {
NODE = 'news/';
news: AngularFireList<News[]>;
constructor(private db: AngularFireDatabase) { }
getAllNews() {
const localNews = this.db.list(this.NODE);
return localNews.valueChanges();
}
getNews(id: string) {
return this.db.object(this.NODE + id);
}
}
news.model.ts
export class News {
id: string;
title: string;
subtitle: string;
article: string;
picture: string;
}
news.component.ts
import { News } from './news.model';
import { Component, OnInit } from '@angular/core';
import { NewsService } from '../services/news.service';
import { Router } from '@angular/router';
import { NavController } from '@ionic/angular';
@Component({
selector: 'app-news',
templateUrl: './news.page.html',
styleUrls: ['./news.page.scss'],
})
export class NewsPage implements OnInit {
news: any;
constructor(private newsService: NewsService, private router: Router, private navController: NavController) { }
ngOnInit() {
this.news = this.newsService.getAllNews();
}
go(id: string) {
this.navController.navigateForward('news/' + id);
}
}
Upvotes: 0
Views: 584
Reputation: 7437
You need to explicitly type what is coming back from the AngularFireDatabase
. You're trying to assign an Observable to EventModel[]
. Observables aren't arrays, but they can emit arrays. Implicit typing for the Observable
is {}
.
What I don't understand is where the EventModel[]
typing is coming from. It's almost like news: any
on news.component.ts was originally news: EventModel[]
and Intellisense is being laggy. Either way, try:
getAllNews() {
const localNews = this.db.list<News>(this.NODE); // now should return Observable<News[]>
return localNews.valueChanges();
}
in news.component:
news: Observable<News[]>;
constructor(private newsService: NewsService, private router: Router, private navController: NavController) { }
ngOnInit() {
this.news = this.newsService.getAllNews();
}
Upvotes: 1