Successfully retrieving data from a web API, however facing challenges with displaying it using Angular2/TypeScript

Having some trouble displaying data from a Web API in my component, can't seem to figure out what's missing.

The service call is successful (received a code 200 with all the applications) List of applications

However, I'm trying to display them in the console and it's not populating the table.

ngOnInit(){
        this.getApplications();
        console.log(this.applications);
    }


getApplications() {
        this.applications = [];
        this._UCCXCiscoService.getApplications().subscribe(
            res => {
                this.applications = res;
            },
                    error => this.errorMessage = <any>error
        );
    }

    // Model

export interface Application {
    self: string;
    ScriptApplication: ScriptApplication;
    id: string;
    applicationName: string;
    type: string;
    description: string;
    maxsession: number;
    enabled: string;
}

export interface ScriptApplication {
    script: string;
    scriptParams: ScriptParam[];
}

export interface ScriptParam {
    name: string;
    value: string;
    type: string;
}

export interface RootObject {
    type: string;
    application: Application[];
}

I believe my model is correct. Seems like there might be an issue with the getApplications() method, but I can't pinpoint why...

Appreciate any assistance,

Florian

EDIT 1 : Code for getApplications() method in my service

@Injectable()
export class UCCXCiscoService {

    public headers:Headers = new Headers({ 'Content-Type': 'application/json' ,'Authorization': 'Basic User + mdp'});

    constructor(private http: Http) {
    }

    getApplications() {
        let options = new RequestOptions({ headers: this.headers });
        return this.http.get('API URL', options)
            .map(data => <Application[]> data.json().application)
            .catch(this.handleError);
    }

This method does work and returns the applications (shown in the image List of Applications). Omitted the api url and password for privacy reasons ^^'

EDIT 2 : getApplications() method in component and service response

EDIT 3 :

<div class="contentPage">
    <div class="pageTitleHeaderContainer">
        <div class="pageTitle">
            <span>Cisco</span>
        </div>
    </div>

    <div class="subContent">
        <message-to-user messageToUser={{messageToUser}} messageLevel={{messageLevel}}></message-to-user>

        <table class="table table-hover table-condensed">
            <th>Id</th>
            <th>Name</th>

            <tr *ngFor="#application of applications">
                <td>{{application?.id}}</td>
                <td>{{application?.applicationName}}</td>
            </tr>
        </table>
    </div>
</div>

Answer №1

When you log to the console in the ngOnInit() method, it occurs before the subscription code runs and before the applications property is populated. To fix this, move the console.log() statement inside the subscribe() arrow function right after setting this.applications = res;

Answer №2

Gratitude to the helpful community, I was able to pinpoint the issue. Initially, my console.log() function was misplaced. After adjusting the ngFor loop to properly display the information, everything is functioning perfectly now!

If you refer to the comment section of my post, you will discover the solution.

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

Building state from multiple child components in Next.js/React: Best Practices

To better illustrate this concept, I suggest checking out this codesandbox link. This is a follow-up to my previous question on Stack Overflow, which can provide additional context. Currently, when interacting with the child elements (such as inputs), th ...

Protractor typescript guide: Clicking an element with _ngcontent and a span containing buttontext

I'm struggling with creating a protractor TypeScript code to click a button with _ngcontent and span buttontext. Does anyone have any ideas on how to achieve this? The code snippet on the site is: <span _ngcontent-c6 class="braeting net-subheadi ...

Angular does not refresh the user interface when there is a modification in the array assigned

Having a <select> that is bidirectionally linked to an array named myArray in the component called MyComponent, I am trying to alter the contents of myArray based on an asynchronous call to a service. When new data is added to myArray using the push ...

Reusing methods in Javascript to create child instances without causing circular dependencies

abstract class Fruit { private children: Fruit[] = []; addChild(child: Fruit) { this.children.push(child); } } // Separate files for each subclass // apple.ts class Apple extends Fruit { } // banana.ts class Banana extends Fruit { } ...

ngIf failing to pick up on variable updates

Utilizing the greensock animation library to animate various components has presented a problem during the variable update within the onComplete function linked to a *ngIf. Strangely, Angular fails to recognize the variable update within the callback. Des ...

Tips on utilizing Selenium with Java to locate and interact with elements on an Angular web application

I'm facing challenges with automating an Angular web app. Despite trying simple code, it still isn't working. Here's an example of my code: @BeforeClass public void setUp() { ChromeOptions options = new ChromeOptions(); ...

What is the best way to structure a POJO for JSON data with both a single field and an array?

I am dealing with the following JSON: { "userName":"<string>", "persons": [ { "id":"<number>", "name":"<string>" } ] } I need assistance in creating a Java POJO to represent this data ...

Having trouble with integrating the Bootstrap Carousel in an Angular 2+ environment

I am currently working with Bootstrap 3.3.7 and Angular 4 for a project. My challenge lies in displaying multiple images in a Bootstrap Carousel, with the aim of showing three images per slide. However, I am encountering an issue where all the images are b ...

Exploring Angular's capabilities with HttpClient and incorporating multiple parameters into a GET request

Using Angular6 for this project. The API I am working with is: https://localhost:44300/list/pete/id/open Within my Angular component, I have a method to call this API: getData(name, id, status): Observable<any[]> { // Setting up Params ...

Strategies for implementing recursive component calling while maintaining nested level monitoring in React Native

Within my application, I have two key components: CommentList and Comment. The CommentList component is responsible for rendering comments by calling the Comment component through a map function, which loops ten times. A unique feature of my app is that e ...

Dealing with the error message "The 'new' keyword requires a constructor signature when targeting a type that does not have one, resulting in an implicit 'any' type.ts(7009)"

Currently, I am in the process of migrating an outdated JavaScript library to TypeScript for integration into Vue 3. However, I encountered an error message that states: 'new' expression, whose target lacks a construct signature, implicitly has a ...

Issues arise when Angular is unable to establish a connection with the backend server written in Golang

Using nginx to serve angular (index.html) is working fine. However, I keep encountering errors when attempting to communicate with my backend. Dockerfile Setup for NGINX + Angular FROM node:12-alpine as builder WORKDIR /usr/src/app COPY . . RUN npm instal ...

Tips for receiving @ mentions in PrimeNg Editor using Quill and quill-mention with Angular

Currently, I have been given the task of adding a mentions feature to our text editors. The editor I am working with is the PrimeNg Editor, built on Quill. After some research, I came across the package quill-mention, which appears to be a potential soluti ...

The continuous re-rendering is being triggered by the Async/Await Function

I am facing an issue with fetching data from the backend using axios. The function is returning a Promise and each time I call it, my component keeps rendering continuously. Below is the code snippet: import { useState } from "react"; import Ax ...

Managing type declarations for two separate yet interlinked projects involves careful attention to ensure consistency and compatibility

My front-end work involves two projects where JavaScript objects from Project 1 are utilized in Project 2. As of now, I have included all the types and methods available in Project 1 into the index.d.ts file of Project 2. However, if I happen to modify a ...

Having trouble importing Angular flex-layout into my feature module

I'm facing an issue with Angular flex-layout in one of my modules. It works perfectly fine when I import flex-layout in the app module, but only for the app component. However, when I import flex-layout in another module, it doesn't seem to work ...

Improving Efficiency in Angular2: Minimize HTTP Requests

Currently, I am utilizing Angular2 RC5 alongside an ASP.NET Core server to handle API calls for data retrieval. My main concern revolves around the number of HTTP calls being made within Angular2 components. I fear that if I continue on this path, the volu ...

When importing the Ionic Native File, the JavaScript File object cannot be used simultaneously

When attempting to use the javascript file object, I encountered an issue because the ionic native file object already uses the same key File Here is an example: import { File } from '@ionic-native/file'; @Component({ selector: 'page-ho ...

Guide on changing the color of the selected item in mat-nav-list within angular 6

Recently diving into Angular 6 and facing an issue with my mat-toolbar integrated with mat-sidenav. Everything seems to be functioning fine, but I'm looking to customize the color for the active item in the side nav menu. Currently, all items have a ...

Using Angular 4 and harnessing the power of RxJS for advanced

Attempting to wrap my mind around RxJS has led me to a question. To gain a deeper understanding of its workings, I initiated a new Angular 4 application created with Angular CLI. Within this environment, I have executed the following code: this.http.get ...