What is the process for extracting the elements of an array fetched from a service in Angular 2?

Currently, I am learning Angular 2 + PrimeNG and going through a quick start project available at the following link: https://github.com/primefaces/primeng-quickstart

The project is a CRUD application and it functions flawlessly. The data is neatly displayed in a table on my browser. It's impressive!

However, as I attempt to make some modifications to the code, everything seems to work fine except for my own code glitch.

export class AppComponent {

    displayDialog: boolean;

    car: Car = new PrimeCar();

    selectedCar: Car;

    newCar: boolean;

    cars: Car[];

    constructor(private carService: CarService) { }

    ngOnInit() {
        this.carService.getCarsMedium().then(cars => this.cars = cars);

        //MY CODE LIES HERE:
        console.log(this.cars);            
        for (let entry of this.cars) {
            console.log(entry);
        }
    }

The initial console.log returns an undefined message while the subsequent for loop disrupts the application flow.

Essentially, I am trying to mirror the data being shown in the browser onto the console. Any assistance would be greatly appreciated!

Thank you! =)

Answer №1

To ensure that your code runs only after the observable result is available, you should move it inside the then(...) block. Otherwise, there's a risk of it executing prematurely.

ngOnInit() {
    this.carService.getCarsMedium().then(cars => {
        this.cars = cars;
        //MY UPDATED CODE:
        console.log(this.cars);            
        for (let entry of this.cars) {
            console.log(entry);
        }
    });
}

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

Kendo Grid with locked height

Using a grid with some elements locked, we have established a CSS-defined minimum and maximum height for the grid. .k-grid-content { max-height: 400px; min-height: 0px; } An issue arises when setting the height of the locked grid. If the grid&a ...

Using TypeScript with Vue to Retrieve Information from a Form

Currently, I am attempting to retrieve data from a form in Vue using TypeScript. However, when declaring the data that I intend to use with this form, it seems to be posted on the fields as shown in this screenshot: message getting posted. I am unsure ho ...

Associating function parameters with object types in TypeScript

In the conclusion of this post, I provide operational code for associating object types with a function that accepts an object containing matching properties. The code snippet I shared results in 'result' being resolved as: type result = { GE ...

Having trouble with serving static files on elastic beanstalk

My angular app works perfectly fine on localhost, but on beanstalk it's not serving all my files. Only index.html and styles.css are found and served, both in a folder called public in the root directory. The build file is located at /build/build.js a ...

I want to learn how to display the rupee symbol instead of the default dollar symbol in AngularJS for specific currency symbols

When using 'currency' in AngularJS, I noticed that a dollar symbol is displayed. How can I change this to show the required currency symbol based on different requirements? Currently, I am looking for information on how to display a rupee symbol ...

Connect a datetime-local typed input to a Date attribute in Angular 2

Can a property of type Date in a component be bound to an HTML5 input with the type attribute set as datetime-local? For example, I have a component with the following property: public filterDateFrom: Date; And in my template, I am trying to bind this p ...

Angular.js Routeprovider for "landing page"

Recently completed an amazing angular js app. Now, I'm looking to create a welcome page for users to start the application from. However, I'm having trouble figuring out how to implement this in my routeprovider since my index.html contains both ...

Using the Angular two-way binding tag within a Spring Boot Thymeleaf application allows for seamless data synchronization between

I have a JSON file where my image is defined like this certLogoURL : "/img/ocjp.gif" I am attempting to show this image in my Thymeleaf template using the following code: <img th:src="@{ {{certificate.certLogoURL}} }" > </img> However, the ...

Using an external npm module in TypeScript can result in the tsc output directory being modified

In my TypeScript project, I have set up the build process to generate JavaScript files in the ./src/ directory. Everything works smoothly when building against existing npm modules, such as Angular 2 imports. However, I encountered a strange issue when I ...

Is it possible to integrate Symfony, Node.js, and Angular into a single application?

Hey there, I am currently working on an audit platform for applications developed using Angular, Node.js, and Symfony. I was wondering if it is possible to use all three technologies simultaneously. You can check out my project in the link below. Thank you ...

Is there a tidier method for coding this JSX?

Is there a way to optimize these function calls for both onGoClick and onNoGoClicked within the SomeForm component? Or is it fine to keep them as they are? <SomeForm onGoClick={() => { cleanupHere(props) }} o ...

RxJS: when combined with timer, groupBy operator does not emit any values

Just starting out with RxJS version 6.5.5, I'm encountering an issue with the groupBy operator. Here's a simplified example to showcase the problem. I have a function called retrieveFiles() that retrieves an array of strings. function async ret ...

Leverage both props and destructuring in your Typescript + React projects for maximum efficiency!

Is it possible to use both destructuring and props in React? For instance, can I have specific inputs like name and age that are directly accessed through destructuring, while also accessing additional inputs via props? Example The desired outcome would ...

The reference to Angular is missing

My current file setup includes an index.html file and an app.javascript file. I keep encountering an error that says "Angular is not defined," even though my script files appear to be properly placed. Below are the contents of my index file and app.js file ...

Angular 6 Error: Template Driven Form - Unable to access property 'required' in null entity

Struggling with validation issues while working on an angular 6 project with a template-driven form. Here is the HTML code snippet causing trouble: <div class="form-group"> <div class="form-group"> ...

Using a universal class URL for all components in Angular 6: Tips and tricks

One common class is imported in all components with a common URL, but the URL appears to not be working. How can I create a common URL for all components in Angular so that changes need only be made in the common class in the future? export class CommonCl ...

Is there a way to trigger an image flash by hovering over a button using the mouseover feature in AngularJS2?

When I hover over the 'click me' button, I want an image to appear on the webpage. When I stop hovering, the image should disappear using the mouseover option. This is what I attempted in my app.component.ts and my.component.ts files: Here is t ...

Building a Custom Dropdown Select List with FormControlName and ControlValueAccessor in Angular 8

Does anyone have a working solution for creating a Material dropdown wrapper (mat-select dropdown) that can be used with formControlName? If so, could you please share a Stackblitz demo of your implementation? Here are the requirements: Should work seam ...

Leveraging a Static HTML landing page template within an Angular 6 application

I currently have an Angular 6 app hosted on example.com, with the dist folder being served on port 5000. Additionally, I have a separate landing page folder with its HTML, CSS, and JS files being served on port 6000 at example.com/welcome. Is there a way ...

Exciting ngClass variation

I am facing a challenge of adding multiple classes to an element, with one of them being conditional. After referencing the documentation, I came across this method: <some-element [ngClass]="{'first': true, 'second': true, 'thi ...