- Forums
- ionic
- [2020] Simple Angular Ionic/Angular App Data JSON API
The is the newest version of 2020 for ionic 4 and angular version 9 to get JSON data from an API from another website [4814], Last Updated: Mon Jun 24, 2024
angular2020
Mon May 04, 2020
0 Comments
447 Visits
This version of this tutorial is for 2020 and the latest version of ionic and angular. for this example, we are using:
$ ionic -v
6.7.0
$ npm -v
6.14.4
Angular CLI: 8.3.26
Node: 12.16.3
OS: win32 x64
Angular: 8.2.14
1. Step one - getting your environement ready. This is easy, just create a blank ionic project. If you don't know how to create a project, make sure you install the requirements above: assuming you have ionic, nodeJS, npm and angular, you can create a new project with these commands:
$ ionic start myApp blank
$ cd myApp
$ ionic serve
Now that we have a blank project, we can start making our edit in the following files. Please note the yellow highlighted text is the code we added to get our JSON data.
app.module.ts - Add imports:
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule,HttpClientModule],
providers: [
StatusBar,
SplashScreen,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule {}
home.component.ts
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
postData;
// url ='https://randomuser.me/api/?results=5'; // alternate FREE JSON SOURCE
url = 'http://jsonplaceholder.typicode.com/posts';
constructor(private http: HttpClient) {}
ngOnInit() {
this.http.get(this.url)
.subscribe( (data) => {
console.log(data)
this.postData=data;
})
}
}
home.component.html
<ion-header [translucent]="true">
<ion-toolbar>
<ion-title>
JSON API POSTS
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content [fullscreen]="true">
<ul>
<li *ngFor="let item of postData">
<h3>{{ item.title }}</h3>
<p>{{ item.body }}</p>
</li>
</ul>
</ion-content>
At the end, you should see something like this picture below