I have an component called customer
which is used to display some data using the api.
For calling the
api
i have created a file calledservices.ts
and it's CODE looks like this:
services.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { IPosts } from './models';
@Injectable()
export class Service {
constructor(private http: HttpClient) {}
public getContactList(): Promise<IPosts> {
const apiUrl: string = 'https://jsonplaceholder.typicode.com/posts'; // dummy API
return this.http.get<IPosts>(apiUrl).toPromise();
}
}
As shown in the code an
interface
(IPosts),I have declared this interface(i,e IPosts) inside an file calledmodels.ts
. The CODE looks like this:
export interface IPosts {
userId: number;
id: number;
title: string;
body: string;
}
Now i am displaying this
api's
data incustomer
component is like this:
customer.html
<div class="container">
<h3>Blog Posts:</h3>
<div class="blogPost " *ngFor = "let post of posts">
<p>{{post.title}}</p>
<p>{{post.body}}</p>
<hr>
</div>
</div>
customer.ts
import { Component, OnInit } from '@angular/core';
import { Service } from '../service';
import { map } from 'rxjs/operators';
import { IPosts } from '../models';
@Component({
selector: 'app-customer',
templateUrl: './customer.component.html',
styleUrls: ['./customer.component.css']
})
export class CustomerComponent implements OnInit {
constructor(public customersServiceList: Service) {}
public async ngOnInit(): Promise<void> {
const posts : IPosts = await this.customersServiceList.getContactList();
console.log(posts);
}
}
I am able see the api's data in the console:
But unable to display it in .html
file . What's wrong in calling the api
.
Here is the stckblitz DEMO
Change CustomerComponent like this
export class CustomerComponent implements OnInit {
constructor(public customersServiceList: Service) {}
posts : IPosts[];
public async ngOnInit(): Promise<void> {
this.posts = await this.customersServiceList.getContactList();
console.log(this.posts);
}
}
Service
public getContactList(): Promise<IPosts[]> {
const apiUrl: string = 'https://jsonplaceholder.typicode.com/posts';
return this.http.get<IPosts[]>(apiUrl).toPromise();
}
It's working check here StackBlitz