Issue with reading the current length of an array object in a while loop in Angular 6

After successfully splitting an array into parts, I decided to add some filters to only include the items in the list that have an action status of (4). However, I encountered a problem where the while loop couldn't read the length of the array.

This is the code snippet I'm using:

  lf = [];
  rows = [];
  size = 4;
  logframes$: any;

  constructor(private logframe: LogicalframeworkService) {
  }

  ngOnInit() {
    this.logframe.getLogicalFrameworks().subscribe(
      data => this.setTitle(data)
    );
  }

  setTitle(array) {
    array.forEach(item => {
      const card = {
        'id': item.id,
        'title': item.project.description
      };
      this.logframe.getAuditTrailStatusByLogFrame(item.id).subscribe(
        (data: any) => {
          if (data.logFrameActionStatusReferenceId === 4) {
            this.lf.push(card);
            console.dir(this.lf);
          }
        }
      );
    });
    while (this.lf.length > 0) {
      this.rows.push(this.lf.splice(0, this.size));
    }
  }

Answer №1

Executing the while loop code prior to the 'logframe' service returning data has been updated in the code. Also, reconsider the necessity of using a while loop for length check as it can be achieved through an if condition.

lf = [];
  rows = [];
  size = 4;
  logframes$: any;

  constructor(private logframe: LogicalframeworkService) {
  }

  ngOnInit() {
    this.logframe.getLogicalFrameworks().subscribe(
      data => this.setTitle(data)
    );
  }

  setTitle(array) {
    array.forEach(item => {
      const card = {
        'id': item.id,
        'title': item.project.description
      };
      this.logframe.getAuditTrailStatusByLogFrame(item.id).subscribe(
        (data: any) => {
          if (data.logFrameActionStatusReferenceId === 4) {
            this.lf.push(card);
            console.dir(this.lf);
            if (this.lf.length) {
              this.rows.push(this.lf.splice(0, this.size));
            }

          }
        }
      );
    });

  } 

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

Displaying grouped arrays efficiently in Angular

I have received data from an API in the form of an array with objects structured like so: [ {"desc":"a", "menu": 1},{"desc":"b", "menu": 2},{"desc":"c", "menu": 1}, ...

Creating a realistic typewriter effect by incorporating Code Block as the input

I am looking to add a special touch to my website by showcasing a code segment with the Typewriter effect. I want this code block not only displayed but also "typed" out when the page loads. Unfortunately, I have been unable to find a suitable solution s ...

Exploring how Jasmine tests the checkbox change handler function in the latest version of Angular (12)

I'm attempting to create a basic test function for a checkbox change event, but I'm encountering some issues running it. The error message states "Spec has no expectations," and the handler function is not included in code coverage. Template: &l ...

Error: Could not find module: Unable to locate 'rxjs/add/observable/throw' in 'D:AngularhttpErrorHandlingExamplesrcapp'

I'm working on an Angular project to practice error handling, but I encountered an issue when trying to import the 'throw' module. The error message reads as follows: Error Message: "ERROR in ./src/app/employee.service.ts Module not found: E ...

Enforcing type safety for mysql2 results in Typescript leads to robust data handling

I have been working on a project using NextJS and Typescript where I need to properly type my MySQL responses. This is the API endpoint I am working with: import { hash } from "bcrypt"; import type { NextApiRequest, NextApiResponse } from "n ...

Instructions for designing a Loading Indicator or Progress Bar within the App Directory of NextJS

Having built a substantial web application using NextJS 13, I initially utilized the Pages Router. However, as I neared completion of the website, I decided to make the switch to the App Directory. The primary motivation behind this migration was not just ...

Securing your Angular2 application with TypeScript for enhanced safety

Looking to create a web application using Angular2 with TypeScript. After researching authentication in Angular2, it seems I need to include the following components: index component (public) login component (public) my private component (private) Thes ...

Guide on utilizing TypeScript interfaces or types in JavaScript functions with vscode and jsdocs

Is there a way to utilize types or interfaces to provide intellisense for entire functions or object literals, rather than just function parameters or inline @type's? For example: type TFunc = ( x: number ) => boolean; /** * @implements {TFunc} ...

When compiling my TypeScript file, I encountered an error stating that a block-scoped variable cannot be redeclared

In my Visual Studio Code, I have written just one line of code in my ex1.ts file: let n: number = 10; Upon compiling using the command tsc ex1.ts, the compiler successfully generates the ex1.js file. However, VSC promptly displays an error in the .ts file ...

Utilizing AWS Amplify with TypeScript and TypeScript Lambdas for powerful web development

Currently, I am working on a project that involves a nextjs frontend with TypeScript and AWS Amplify for the backend. My intention is to write my Lambda functions in TypeScript as well. However, I have encountered an issue where I have one tsconfig.json fi ...

Discovering the specific p-checkbox in Angular where an event takes place

Is there a way to assign an ID to my checkbox element and retrieve it in my .ts file when the checkbox is selected? I want to pass this ID along with the true or false value that indicates if the checkbox is checked. Here's an example code snippet: &l ...

I'm looking to find the Angular version of "event.target.value" - can you help me out?

https://stackblitz.com/edit/angular-ivy-s2ujmr?file=src/app/pages/home/home.component.html I am currently working on getting the dropdown menu to function properly for filtering the flags displayed below it. My initial thought was to replicate the search ...

What is the best way to retrieve a value from async/await functions?

async function fetchNetworkStatus() { const network = await Network.getConnection(); setConnection(network.isConnected); console.log(connectionStatus); if (network.isConnected) { return true; } else { ...

Is it possible that multiple identical queries are being executed in succession when adjusting the amount of data being displayed?

Why do multiple identical GET requests get executed when changing the data amount? [HPM] GET /api/users/get_all?search=&order=asc&pageSize=25&page=1 -> http://localhost:5000 GET /api/users/get_all?search=&order=asc&pageSize=2 ...

Encountering an issue when attempting to attach an event listener to the entire document

I need help troubleshooting an issue with a function that is supposed to perform certain operations when the scrollbar is moved. I attached an event listener to the document using an ID, but it's resulting in an error. ERROR Message: TypeError: Canno ...

The build error TS1036 is thrown when a function with a return statement is moved to index.d.ts, even though it worked perfectly in a standard TS file

In my project using Node v14.x and StencilJS (React) v2.3.x, I encountered an issue with a test-helper file containing a function that converts string-arrays to number-arrays: export function parseNumericStringOrStringArrayToIntegers(value: string | (strin ...

Circular function reference in Typescript occurs when a function calls itself

The functionality of this code snippet is rather straightforward; it either returns a function or a string based on an inner function parameter. function strBuilder(str: string) { return function next(str2?: string) { if(typeof str2 === "string& ...

The TS2339 error has occurred because the "email" property cannot be found on the specified "Object" type

I encountered an issue while using Angular 5, here is the code snippet : signIn(provider) { this._auth.login(provider).subscribe( (data) => { console.log(data); this.hideForm = false; this.emaill = data.email; ...

What is the process for performing type checking on an array variable designated as "as const"?

Check out this code snippet: export type Types = 'a' | 'b'; export type MyPartials = { readonly [P in keyof Types]?: number; }; export interface MyI { readonly name: string; readonly myPartials: MyPartials; } export const myI ...

When submitting a form, the MEAN STACK backend is storing the objectId and __v : 0 in MongoDB

Currently, I am developing a small CRUD application using the MEAN STACK framework. My goal is to create a form that allows me to store book information in MongoDB. However, upon submission, I noticed that instead of saving the book's details, the dat ...