The code within a for loop may not function properly when placed within the ngOnInt() function

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 ;   
   
    }

Answer №1

It seems like there may be an issue with how you are accessing the array in your code. Consider trying one of the following approaches:

ngOnInit(): void {
     for(let news of this.getAllNews){
       console.log(news.Info);//Assuming Info is a property.
     }
   }

OR

ngOnInit(): void {
         for(let news in this.getAllNews){
           console.log(this.getAllNews[news].Info);//Assuming Info is a property.
         }
       }

Please review and test these options, and let me know if it resolves the issue.

Answer №2

Practical demonstration using real data

Check out this sample for manipulating arrays in angular. It is guaranteed to work flawlessly even with extensive value lists.

Kindly review the linked image for further clarification.Enhanced the logic using authentic data

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Connecting multiple TypeScript files to a single template file with Angular: A comprehensive guide

Imagine you are working with a typescript file similar to the one below: @Component({ selector: 'app-product-alerts', templateUrl: './product-alerts.component.html', styleUrls: ['./product-alerts.component.css'] }) expo ...

Angular's change detection is currently inactive

I need to toggle the visibility of a button based on the value of a boolean variable using the Output property. However, I am facing an issue where the button remains hidden even after the variable is updated with a true value. Parent Component.ts showE ...

Creating a module within a component in angular - step by step guide

I am interested in dynamically creating a component inside another component. This will allow me to pass my dynamic HTML template directly to the decorator like this: //code /** * @param template is the HTML template * @param container is @ViewChild(& ...

Explore Angular's ability to transform a nested observable object into a different object

My task involves mapping a field from a sub object in the response JSON to the parent object The response I receive looks like this: { "id": 1, "name": "file-1", "survey": { "identifier": 1, "displayedValue": survey-1 } } I am attempting ...

Leveraging components from external modules within sub-modules

So, I've created a module to export a component for use in different modules. However, I'm facing an issue with how to properly utilize this component within child modules of another parent module. While I have imported the first module into the ...

Step-by-step guide for integrating Google Closure Library with Angular 10

Is there a way to integrate the Google Closure Library into an Angular 10 project? I attempted to install it using npm install google-closure-library, but encountered an error stating Could not find a declaration file for module 'google-closure-librar ...

A guide on the correct way to fork an Ionic Stencil Component

I am interested in customizing the columns and position of ion-datetime to use it in my Ionic app. However, I am unsure how to approach this without resorting to messy copy-and-paste solutions. Are there any better methods for achieving this customizatio ...

Perform a series of observables from a dynamically generated array

Currently, I am in the midst of a project (Angular2) where I am dynamically creating Observables and storing them in an array. var ObservableArray : Observable<any>[] = []; //populating the Observable array dynamically for (var i = 0; i < this.ma ...

Retrieve the API output and save the information into an array

I am struggling with calling an API in my Angular application and extracting specific data from the JSON response to populate an array. Although I am able to retrieve the response, I am having trouble isolating a particular field and storing it in an array ...

Having difficulty retrieving values while using async-await

Utilizing the code below has been successful for me. I managed to retrieve the data in the spread (then), returning a http200 response. Promise.all([ axios({ method: 'post', url: 'https://oauth2.-arch.mand.com/oauth2/token&a ...

What is the best way to define a named, optional parameter in TypeScript-React that can accept an object with optional fields and default values?

Is there a way to achieve something similar to the style property found in default HTML components? For instance: <div ref={ref} style={{ overflow: 'visible', height: 600, width: '100%' }}> The style prop is optional, and the fie ...

Ways to help a child notice when a parent's variable changes

Looking for help with passing data to a child component? Check out this Plunker: http://plnkr.co/edit/G1EgZ6kQh9rMk3MMtRwA?p=preview @Component({ selector: 'my-app', template: ` <input #x /> <br /> <child [value] ...

Move the cursor to the end of the text when the key is released

I've developed a feature similar to that of a command line interface. When you input commands and hit the up key, the previous command is displayed. Everything is functioning as intended, but there's one minor issue. The current problem I'm ...

Retrieve the instance from the provider using its unique key without needing to inject its dependencies

I created a custom class called PermissionManager, which takes a list of Voter interfaces as an input in its constructor. export interface Voter { vote(): bool; } export class PermissionManager { constructor(private readonly ...

NGRX refresh does not result in any successful actions

Having an issue with loading users into a mat-selection-list within a form. Everything works fine the first time, but upon page refresh, the selector returns 'undefined'. Initially, both GET_USERS and GET_USERS_SUCCESS are triggered (console log ...

The `Required<Partial<Inner>>` does not inherit from `Inner`

I stumbled upon a code snippet that looks like this: type Inner = { a: string } type Foo<I extends Inner> = { f: I } interface Bar<I extends Inner> { b: I } type O<I extends Partial<Inner>> = Foo<Required<I>> & B ...

How can I retrieve properties from a superclass in Typescript/Phaser?

Within my parent class, I have inherited from Phaser.GameObjects.Container. This parent class contains a property called InformationPanel which is of a custom class. The container also has multiple children of type Container. I am attempting to access the ...

How to inject a regular class in Angular2 without the @Injectable decorator

angular: 2.0.0-beta.9 Can we inject a non-@Injectable class into a component? For instance, if this class originates from an external Third party library. ...

Utilizing useLocation for Defining Text Styles

I'm currently integrating TypeScript into my project, but I'm encountering an error related to 'useLocation' in my IDE. Any thoughts on what might be causing this issue? import React from "react"; import { useHistory, useLocat ...

Error occurs when the directive is not being applied due to the usage of the "attr" host attribute

Referring to a post about host attributes, I have developed a Plunker for demonstration purposes. Upon reviewing the github issue, it seems that using [attr.someDirective] should allow us to selectively apply a directive attribute to an element. Although ...