The Angular ngFor loop seems to be stuck in an endless cycle while trying to display

I'm currently in the process of creating a Logbox for my web application. It is designed to receive an Array of logs and display them row by row within a div. I am utilizing ngFor to iterate through my Array of logs and then present them.

However, I've encountered a problem where the logs are being displayed infinitely instead of just 5 times (corresponding to the 5 entries in the list).

Does anyone have any insights into what I might be overlooking?

logs.component.html

<div class="logContent">
    <div class="row">
      <div class="col-12" *ngFor="let log of this.logService.getLogs()">
        <app-singlelog [when]="log.when" [type]="log.type" [data]="log.data"></app-singlelog>
      </div>
    </div>
  </div>

log.service.ts

export class LogService {
  private logArray = [];

  constructor(private httpservice: HttpserviceService) { 
    
  }

  public getLogs(): Array<Log> {
    this.httpservice.getLogs().subscribe(data => {
      data.forEach(index => {
        let logObject = {} as Log;
        logObject.when = index.when;
        logObject.type = index.type;
        logObject.data = index.data;
        this.logArray.push(logObject);
      })
    }
    )
    return this.logArray;
  }
}

Thank you :)

Answer №1

Avoid using function calls directly in the html template to display data.
Instead, invoke the getLogs() function from the Angular component's ngOnInit() lifecycle hook, and save the response in a variable. Then iterate over that variable:

export class LogService implements OnInit {
// ...

logs = [];

ngOnInit() {
   this.getLogs();
}

getLogs(): Array<Log> {
    this.httpservice.getLogs().subscribe(data => {
      data.forEach(index => {
        let logObject = {} as Log;
        logObject.when = index.when;
        logObject.type = index.type;
        logObject.data = index.data;
        this.logArray.push(logObject);
      });
      // store the response in logs array:
      this.logs = data;

    });
}

In the HTML template:

 <div class="col-12" *ngFor="let log of logs">
   <app-singlelog [when]="log.when" [type]="log.type" [data]="log.data"></app-singlelog>
</div>

The rationale behind this approach is that Angular triggers your getLogs function on every page rendering cycle. However, it's preferable to make the http request only once, during component initialization.

Remember to unsubscribe from your Observable. ;) - noted from the feedback below.

Answer №2

To take a more dynamic approach, you can implement the following reactive method:

Start by defining the observable within your component:

logs$ = this.logService
    .fetchLogs()
    .pipe(
      shareReplay(),
      map((response) => response.map(({ timestamp, level, message }) => ({ timestamp, level, message }))
    );

Incorporate the following into your component's HTML structure:

<div class="col-12" *ngFor="let log of logs$ | async">
   <app-log [timestamp]="log.timestamp" [level]="log.level" [message]="log.message"></app-log>
</div>

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

Set the height of CSS3 to 100% full

I'm struggling to articulate my question, so please feel free to suggest a better title or guide me in the right direction. I'm working on a website using a mix of HTML5 and CSS3, and I want it to display consistently across various browsers. H ...

Encountered an unexpected token error while using Jest with TypeScript, expecting a semicolon instead

I have been struggling to configure jest for use with typescript and despite trying several solutions, I am still facing issues. The error SyntaxError: Unexpected token, expected ";" keeps popping up, indicating that the configuration may not be compatible ...

Troublesome situation arising from CSS floats overlapping div elements

It's strange how this issue always occurs when using floats. This is what my div (samle) looks like: <div class="main> <div class="inn_div">&nbsp</div> </div> Here is my stylesheet: .main{ width:250px; border:1px ...

Add a transition or animation effect to the <details> element as it closes

I am experimenting with adding a transition effect to the details element when it opens and closes: details { height: 1em; transition: height 2s; border: 1px solid; overflow: hidden; white-space: pre; } details[open] { height: 6em } <det ...

Unraveling CSS inheritance: A guide to overriding inherited styles

I need to make some adjustments to a WordPress template. One of the changes is to set the background color of an element to transparent. The wrapper div, which has the background color applied to it, contains many nested child divs that all inherit that co ...

What is the best way to retrieve JSON data from a raw.github URL and save it into a variable?

Suppose there is a JSON file named data.json on Github. The raw view of the file can be accessed through a URL like this: https://raw.githubusercontent.com/data.json (Please note that this URL is fictional and not real). Assume that the URL contains JSON ...

What is the best way to store selected items from a multi-select box in AngularJS that is generated using ng-repeat?

I have a scenario where I need to handle a group of select boxes instead of just one. Each select box holds a different option, and when the user changes their selection, I want to save that value in a variable or an array. I've managed to do this for ...

The chart JS label callback requires a specified type declaration

Currently, I am in the process of updating an old Angular platform to a newer version. One requirement is that everything must have its type declaration. I encountered a problem with the label callback showing this error: The error message reads: "Type &a ...

Guide to setting the current slide in your ngx owl carousel using Angular

Looking for a solution to dynamically set an active slide based on index within a carousel. Attempted to apply the classes "active" and "center". The newsId variable in the example below is retrieved from another page and has been verified. <owl-carouse ...

Is it feasible to have a set number of character lines per <p> tag without relying on monospaced fonts?

I am facing the challenge of breaking a large text into paragraphs of equal size, with the same number of string lines in order to maintain uniformity. Currently, I am using PHP and the following code to achieve this: function arrangeText(){ if (have_ ...

How to perfectly center an element with a specified aspect ratio

I am experiencing a strange problem when attempting to center an element with aspect-ratio applied. I thought it would work similar to centering an image, but I keep getting stuck with an element of 0px x 0px. https://codepen.io/richardcool/pen/xxeKOwp I ...

Diverse positioning across various browsers

I have a navigation menu with alternating divs - one containing a menu link and the other a 'menu separator' div with a 2px wide 'separator bar' image. The width of the separator divs is set to 24px to create proper separations. For so ...

The value produced by the interval in Angular is not being displayed in the browser using double curly braces

I am attempting to display the changing value on the web page every second, but for some reason {{}} is not functioning correctly. However, when I use console.log, it does show the changing value. Here is an excerpt from my .ts code: randomValue: number; ...

Why does HTML validation matter after the webpage has finished loading?

After coming across an article recommending a workaround for a method that isn't considered strictly valid (using target="_blank") by using JavaScript to apply the rules after the page has loaded, I began contemplating if this approach is ethical. It ...

Code snippet for replacing text enclosed between two tags using regex in PHP programming language

While I am not an expert in regex, I am attempting to develop a code inspired by examples I have come across. My goal is to replace instances of the string <li> with <li class="ingredient"> within a WordPress table. However, this replacement mu ...

Encountering TypeScript Observable Error When Sending Multiple API Requests (Angular, TypeScript, RxJS)

Encountering an Issue: ERROR in src/app/fetch-trefle.service.ts:86:31 - error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. 86 mergeMap((item: any): Observable<any> => { Here& ...

Utilizing complex data with Angular 5 [Select+Option] - a comprehensive guide

I have a complex dataset stored in the app.component.ts file that looks like this: export class AppComponentimplements OnInit { tests = { 'name': 'Bob', 'grade': '5th', 'score' ...

Removing the &nbsp; space character from a webpage using server-side code

I am experiencing difficulties with replacing a blank space in a webform control label. Below is the code for my label: <label id="Lbl1" runat="server">TEXTA&nbsp;&nbsp;TEXTB</label> My goal is to replace the blank spaces in the labe ...

JQuery requests functioning flawlessly on one system while encountering issues on other systems

I've encountered an issue with the code on my admin page. It used to work perfectly fine on my system, but now it seems to have stopped functioning. My client urgently needs to update this page, however, when I attempt to run it, the JQuery requests a ...

Dropdown menu change event malfunctioning

I am facing an issue with my HTML form that contains multiple text fields and dropdowns. I need to loop through all the dropdowns for validation purposes. Initially, only the first dropdown is visible when the page loads. The rest of the dropdowns become v ...