Correct way to display data from Rest Api in Angular

angular 7 get data from api
how to fetch data from database in angular 8
how to get data from api in angular 6
how to fetch data from database in angular 6
angular get data from api
angular 6 rest api example
angular 4 get data from api
angular 6 post data to web api

I have have a service in Angular, which calls data from an API. So when I am trying to display the data it is not displaying?

Service

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, of, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

@Injectable()
export class ApiService {

   api: string = 'https://newsapi.org/v2/top-headlines?country=gb&category=entertainment&apiKey=8ee8c21b20d24b37856fc3ab1e22a1e5';

  constructor(
    private http: HttpClient,
  ) { }

getAll(): Observable<any> {
    return this.http.get(this.api)
    .pipe(
      catchError(this.handleError)
    );
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.log(error.error.message)

    } else {
      console.log(error.status)
    }
    return throwError(
      console.log('Something is wrong!'));
  };
}

Component.ts

import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  public data = [];
  public noData: any;
  public results = [];

  constructor(
  private api: ApiService 
  ){ }

  getAll() {
    this.api.getAll().subscribe((results) =>  {
      this.data = results.results;
      console.log('JSON Response = ', JSON.stringify(results));
    })
  }

 ngOnInit() {

  }
}

JSON response structure

{ 
   "status":"ok",
   "totalResults":70,
   "articles":[ 
      { 
         "source":{ 
            "id":null,
            "name":"Thesun.co.uk"
         },
         "author":"Mary Gallagher",
         "title":"Holly Willoughby breaks down in tears on This Morning as she meets disabled boy who speaks against all odds - The Sun",
         "description":"",

etc etc

HTML

<div *ngFor="let news of data">
   <h3>{{news.json}}</h3>
</div>

Where Am I going wrong?


articles is a property of data, so you have to loop data.articles

Try like this:

<ng-container *ngFor = "let news  of data?.articles">
  <h3>{{news.title}}</h3>
</ng-container>

Another option:

TS:

this.data = results.articles;  // here now you have list of all articles

HTML:

*ngFor="let news of data"

Working Demo

Consuming APIs in Angular: Displaying Data In Components, Here are the steps we'll take to do it: Import the service. Inject it in the component using Angular's dependency injection. In the component's ngOnInit() method, get the RxJS observable to the list of course and subscribe to it. Store the fetched list of course on the component so that it gets rendered in the template In this Angular 8 tutorial, we will show you a comprehensive step by step Angular 8 tutorial on consuming REST API using Angular HttpClient. As you see in almost Angular or MEAN stack tutorial in this site always uses REST API access. So, we will cover more details about consuming the REST API using Angular HttpClient and other required modules.


When you ask for a "correct" way, it is commonly recommended to avoid subscriptions in component when you don't have to. Prefer asyncpipe instead.

import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  public data$: Observable<Data[]>;

  constructor(
    private api: ApiService 
  ){ }

 ngOnInit() {
    this.data$ = this.api.getAll();
  }
}

<ng-container *ngIf="data$ | async as data; else pending">
  <div *ngFor="let article of data.articels">
     <h3>{{news.json}}</h3>
  </div>
</ng-container>

<ng-template #pending>
  <div>pending</div>
</ng-container>

Advantage: You never forget to unsubscribe, you have easy control over pending state

Angular 8/7 Tutorial By Example: (REST API, HttpClient GET , In this Angular 8/7 tutorial, you'll learn by example how to send GET requests services and how to use the ngFor directive to display collections of data. to third-party REST API servers and how to consume and display the� To display data in Angular, we can use the Angular httpclient module to send a network request to a server and fetch the data and then use the ngFor directive to render the data to the frontend. If you are new to Angular 9, then check out this Angular 9 CRUD Tutorial article. Let’s see one by one step to display data in Angular 9.


Please check once

<div *ngFor="let news of data.articles">
   <h3>{{news.author}}</h3>
</div>

Real-World Angular Series, We have data in our database, so it's time to retrieve it with the API. We'll start by writing four We need ENV from our environment config to get the appropriate API URIs. Finally, in order to "Angular CLI supports scaffolding components in a variety of ways using flags." Look forward to following the rest. See solution below: I'm trying to connect to a Parse.com Rest backend and display data from object values. HTML (I put several angular calls to be sure to catch output): &lt;div ng-controller="


It looks like you are assigning object response, not array. So try to assign array:

this.data = results.results.articles;

OR add articles to iterate through array of articles:

<div *ngFor="let news of data?.articles">
   <h3>{{news.json}}</h3>
</div>

Angular 8 : HttpClient -REST API call, This video explain you How to make a rest call from Angular using HttpClient and mapping Duration: 6:02 Posted: Aug 7, 2019 Phase 2: Programming the Angular 6 REST API Client. In this phase, we will see, how easy it is in Angular 4.3+ to 6 to retrieve and display data from a REST API. Step 2.1: Add HTTP Client Module. First, we need to tell Angular that we will use the HttpClientModule. For that, we edit src/app/app.module.ts (added parts in blue).


With this JSON response:

{ 
   "status":"ok",
   "totalResults":70,
   "articles":[ 
      { 
         "source":{ 
            "id":null,
            "name":"Thesun.co.uk"
         },
         "author":"Mary Gallagher",
         "title":"Holly Willoughby breaks down in tears on This Morning as she meets disabled boy who speaks against all odds - The Sun",
         "description":"",

Your component should be:

import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  public data = [];
  public noData: any;
  public results = [];

  constructor(
  private api: ApiService 
  ){ }

  getAll() {
    this.api.getAll().subscribe((results) =>  {
      this.data = results.articles;
    })
  }

 ngOnInit() {

  }
}

Your template:

<div *ngFor="let news of data">
   <h3>{{news.json}}</h3>
</div>

Angular Tutorial - 21 - Fetch Data Using HTTP, Angular | Angular Tutorial for Beginners | Fetch Data Using HTTP. Loading Autoplay When Duration: 8:36 Posted: Jan 8, 2018 Introduction to the Angular Material Data Table. The Material Data Table component is a generic component for displaying tabulated data. Although we can easily give it a Material Design look and feel, this is actually not mandatory. In fact, we can give the Angular Material Data table an alternative UI design if needed.


Communicating with backend services using HTTP, Angular provides a simplified client HTTP API for Angular applications, the HttpClient service Use the HTTPClient.get() method to fetch data from a server. spCustomerController – Angular controller defined to bind within the module. GET – REST Api method to fetch the data from the list. Accept”: “application/json;odata=verbose – REST Api header defined. _spPageContextInfo.webAbsoluteUrl – This will return a web absolute url of the site


Get data from a server, Important: the In-memory Web API module has nothing to do with HTTP in Angular. getHeroes() method should catch errors and do something appropriate. callback receives the new hero and pushes it into to the heroes list for display. The rest of it closely resembles getHeroes() , the only significant difference being� Updates 19.09.2018 - Updated Angular Syntax 19.08.2017 - Updated to ASP.NET Core 2.0 & new HttpClientModule Blogpost Hey, with this blog pot I want to show you how to create a dataservice to consume (not only) an ASP.NET REST API with the angular http module. In my recent blog post Getting started with Visual Studio Code, AngularJS and Typescript I have already mentioned how to start and to


Angular HttpClient (6/7/8/9/10): Consume REST API Example, Create Angular Service for consuming REST API using Angular will show you in an easy way and a little bit different from the original Angular docs. Add a function to POST new product data to the REST API using Angular HttpClient text-decoration: none; position: relative; display: block; width: 250px;�