Step 1. Link api json
https://raw.githubusercontent.com/anhtt-asiantech/gnd.io/fb75e146f01b567129bd2acb7bdeff9d6ab9c6a0/public/demos/routes/data/families/birds.json
Step 2. Create a class Bird.ts
export class Bird{
id : number;
name : string;
type : string;
ScientificName :string;
}
Step 3. Folder app
1. app.module.ts
Import libary httpClientModule
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [ BrowserModule, FormsModule,HttpClientModule ],
declarations: [ AppComponent, HelloComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
p {
font-family: Lato;
}
<div style="text-align:left;width:500px;">
<h1>
{{ title }}!
</h1>
<table *ngIf="arrBirds">
<!-- ADD HEADERS -->
<tr>
<th>ID</th>
<th>Name of Bird</th>
<th>Type of Bird</th>
</tr>
<!-- BIND ARRAY TO TABLE -->
<tr *ngFor="let bird of arrBirds">
<td>{{bird.ID}}</td>
<td>{{bird.Name}}</td>
<td>{{bird.Type}}</td>
</tr>
</table>
</div>
import { Component } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { HttpErrorResponse } from '@angular/common/http';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import {Bird} from './Bird';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Reader json ';
arrBirds: Array<Bird>;
bird : Bird;
constructor(private httpClient : HttpClient){
}
ngOnInit (){
this.httpClient.get('https://raw.githubusercontent.com/anhtt-asiantech/gnd.io/fb75e146f01b567129bd2acb7bdeff9d6ab9c6a0/public/demos/routes/data/families/birds.json').subscribe(
data => {
//this.arrBirds = data as string []; // FILL THE ARRAY WITH DATA.
this.arrBirds = data as Array<Bird>;
// let resources = data["resources"];
for(let i =0;i<this.arrBirds.length;i++){
let resource = data[i];
console.log(resource["Name"]);
}
},
(err: HttpErrorResponse) => {
console.log (err.message);
}
);
}
}
Demo Tutorial reader json angular example.
No comments
Post a Comment