Unable to connect with API data in Angular 6

I have been using an API to retrieve data and display it on a webpage. While I am able to see the response in the console, I am facing difficulty binding the data to the user interface. Nothing is appearing on the screen as expected.

This is my HTML code:

<ul *ngFor="let item of items; let i = index">
 <li class="fa fa-plus">{{item.name}} - {{i}}</li>
</ul>

And this is my TypeScript code:

id: number;
name:string;
imageUrl: string;
items:any = {}; 
ngOnInit() {
this.getItems();
}
getItems() {
this.getItemsService.getItems().subscribe(
  res => {
    console.log(res)
    if (res.Success) {
      this.items = res;
    }
  }
)

}

I have defined the 'items' variable as an object because I am trying to fetch data from an array of objects. Even when I tried defining it as an array, I still face the same issue of not being able to bind data to the HTML.

This is the link to the API I am using:

If you need any more information or have questions, please feel free to ask. I would greatly appreciate any help with binding this data effectively.

Answer №1

Let's talk about two things starting with HTML: the syntax for `let i = index`.

Secondly, there is a condition in your binding:

if (res.Success) {
  this.items = res;
}

This suggests that your response should have a property named `Success`.

However, after checking your API link, it seems like it doesn't exist.

To resolve this issue in your service, you can either use `Http from @angular/http` or `HttpClient from @angular/common/http`. Here are the two different syntaxes to consider:

// Http
return this.http.get('url').map(res => res.json());
// HttpClient
return this.http.get<any[]>('url');

As for the condition, modify it as follows to ensure data presence. There's no need to check for success because you already have a specific callback function for that purpose. This means that when the condition is met, you will always have succeeded.

if (res) {
  this.items = res;
}

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

Troubleshooting: Issues when using jQuery metisMenu in conjunction with *ngIf

We are facing an issue while using the metisMenu with Angular2. There is an *ngIf condition on one of the list items, and its visibility changes based on whether a record is selected. When the li item is shown for additional options, it does not work prope ...

Issue with Fat-Free Framework and Abide AJAX form submission malfunction

Currently, I am utilizing Foundation 5.5.3 and Abide form validation in order to facilitate site registration. This is reflected in my Javascript code below: $('form#register').on('valid.fndtn.abide', function() { var data = { ...

Determine the Mean of Every Set of Values Extracted from a Document

Currently, I have a program that reads data from a text file and displays a list of numbers in a list box. Now, I need to enhance the program to calculate the average of each series of numbers, where each series is separated by a 0. I plan to store the dat ...

Angular's mechanism for detecting changes in a callback function for updates

I have come across a puzzling scenario regarding a basic issue. The situation involves a simple component with a boolean property that is displayed in the template of the component. When I update this property within a callback function, the property is up ...

Discovering various kinds of data with a single generic type

I am looking to define a specific type like this: type RenderItems<T> = { [K in keyof T]: { label: string; options: { defaultValue: T[K]['options'][current_index_of_array]; item: (value: T[K][&apo ...

Choosing the image that represents your website in Safari web previews

Every time I check iCloud.com on my Safari top sites, the thumbnail is always the same. I'm curious about how I can automate this for my own website. ...

Text input field that adjusts its width based on content and remains

I am attempting to design a div that contains a fluid-width textarea. The div should have a width of at least 3em, maximum of 12em, and adjust accordingly to the width of the textarea. I have successfully implemented this. Check out the fiddle. However, w ...

Guidelines on launching an ionic 4 modal using routes

How can I open a modal using routes? I attempted the following approach, but it did not work as expected: ngOnInit() { this.launchModal(); } async launchModal() { const modal = await this.modalController.create({ component: AuthPasswordR ...

Receiving null value with Web API POST using [FromBody]

Below is the code for my WebAPI in C#: [Route("")] [HttpPost] public void SaveTestRun([FromBody] object data) { inputResultsToDatabase(data); } This is the ajax request I am making: sendTestData() { t ...

Robotic Arm in Motion

GOAL: The aim of the code below is to create a robotic arm that consists of three layers (upper, lower, and middle), all connected to the base. There are four sliders provided to independently move each part except for the base which moves the entire arm. ...

Allow consumers of the component to customize the ChangeDetectionStrategy

Imagine a scenario where a component in a UI library is configured with ChangeDetectionStrategy.Default, but wants to offer the flexibility for consumers to switch to ChangeDetectionStrategy.OnPush (especially for performance considerations) using an Input ...

Experiencing SyntaxError when utilizing rewire and mocha for Node.js testing. Unexpected token encountered

Trying to test a function exported from a nodejs file, I am utilizing q to manage promises. The function returns a promise that is either resolved or rejected internally through a callback. Within this callback, another function from a different location i ...

Angular Oops! We ran into a small hiccup: [$injector:modulerr]

I am facing an issue with an angular js error angular.js:36 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.19/$injector/modulerr?p0=app&p1=Error%3A%20…gleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.19%2Fangular.min.js%3A18%3A139) ...

Understanding File Reading in Angular/Typescript

I'm currently developing an app similar to Wordle and I'm facing an issue with reading words from a file. Here's what I tried: import * as fs from 'fs'; const words = fs.readFileSync('./words.txt', 'utf-8'); con ...

What is the best way to set the position of a button in TypeScript React?

I'm currently working on positioning a button in TypeScript React. Here is the code I have written so far: <Button key="copy-to-clipboard" id="copy-to-clipboard" text="Copy" icon="file_copy" ...

Ways to resolve the error "Expected an assignment or function call but found an expression with no-unused-expressions"

Issue : Error in ./src/components/main.js Line 7: No function call or assignment found, only an expression is present (no-unused-expressions) Search for the specific keywords to get more information on each error. import React from 'react'; ...

Remove the JSON object from the screen in an asynchronous manner

I am currently working on developing a single-page application that retrieves information from a JSON file, displays it on the screen, and performs various actions. At this point, all the information is being properly displayed on the screen: http://jsfid ...

HTML and CSS: Understanding DataTables Header Padding

http://jsfiddle.net/d1zqsayh/ (Strange issue not appearing on jsfiddle, very odd) When I modify the padding in the .css file at line 41 from 10px 18px; to 10px 17px;, I notice a difference in how the content is displayed on my screen in both Google Chrome ...

Mapping the preselected values of multiple input fields into an array in Angular 6: A step-by-step guide

When submitting a form with input fields, I need to capture the selected values into an array format like {"userid":1,"newstatus":[1],"mygroup":[1,2,3]}. I attempted using ngmodel but encountered issues. Below is the code snippet: home.component.html & ...

Searching for real-time data with ajax. Strategies for showing alternative results when there is no user input

I am currently working on developing a live search feature using technologies like ajax, jQuery, PHP, and MySQL. The user inputs certain queries which are then sent to form_livesearch.php where the search is processed. I have successfully implemented this ...