I am struggling with running a for loop inside ngOnInit in Angular. I have a service that has a method getAllNews() which returns an array, not an observable. Since I can't use the subscribe() method, I want to iterate over this array. When I console log getAllNews, it displays the array correctly, but when I try to loop inside this array, nothing works, not even a simple console.log(). I have tried using for and forEach loops, but something seems to be missing. As I am new to Angular, I can't figure out what is wrong. Below is my component.ts file:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { element } from 'protractor';
import { CovidService } from '../covid.service';
import { News } from '../models/news.model';
@Component({
selector: 'app-inside-news',
templateUrl: './inside-news.component.html',
styleUrls: ['./inside-news.component.css']
})
export class InsideNewsComponent implements OnInit {
getAllNews: any[] = []
currentNews: News = new News(new Date,"","","","") ;
current: any ;
constructor(private covidService : CovidService , private route : ActivatedRoute , private router
: Router) { }
ngOnInit(): void {
this.current = this.route.snapshot.paramMap.get('title') ;
this.getAllNews = this.covidService.getAllNews()
console.log(this.getAllNews)
for(var element in this.getAllNews)
{
console.log(this.getAllNews[element])
}
}
}
I also tried another approach, but faced the same issue. The first console log in the function displayed the full array with data, but the second console.log inside the loop did not work as expected:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { element } from 'protractor';
import { CovidService } from '../covid.service';
import { News } from '../models/news.model';
@Component({
selector: 'app-inside-news',
templateUrl: './inside-news.component.html',
styleUrls: ['./inside-news.component.css']
})
export class InsideNewsComponent implements OnInit {
getAllNews: any[] = []
currentNews: News = new News(new Date,"","","","") ;
current: any ;
constructor(private covidService : CovidService , private route : ActivatedRoute , private router
: Router) { }
ngOnInit(): void {
this.getCurrentNews() ;
}
getCurrentNews() {
this.current = this.route.snapshot.paramMap.get('title') ;
this.getAllNews = this.covidService.getAllNews()
console.log(this.getAllNews)
for(var element in this.getAllNews)
{
console.log(this.getAllNews[element])
}
}
}
This is the array I am getting and trying to loop through when I console log getAllNews()
View the getAllNews array image here
This is the function in the service:
getAllNews(){
let news = firebase.firestore().collectionGroup("news") ;
let newsData : any[] = [] ;
let test : any ;
news.get().then((querySnapshot)=>{ querySnapshot.docs.forEach( element =>{
newsData.push(element.data())})}) ;
// console.log(newsData)
return newsData ;
}