I am beginner in ionic 4. And I am trying to get json data from an api using native http. My code is working fine with a json data response, but the problem is I got empty data in html
json
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
main code :
import { Component } from '@angular/core';
import { HTTP } from '@ionic-native/http/ngx';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
object : any ;
constructor(private http: HTTP) {
this.http.get('https://jsonplaceholder.typicode.com/todos/1',{},{})
.then(res=> {
this.object = res.data
}) .catch(error => this.object = error);
}
}
if l use only object in html he is return json response
{{object}}
but if l want get title form data json l got empty page
{{object.title}}
No need to use the plugin, you can do this with stock Angular
main.code
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
public theTodo: any;
private _productURL = 'https://jsonplaceholder.typicode.com/todos/1';
constructor(
private http: HttpClient
) { }
ngOnInit() {
this.http.get(this._productURL).subscribe(data => {
this.theTodo = data ;
});
}
}
and the html
<ion-content padding>
{{theTodo?.title}}
</ion-content>
I would extend this code to create an interface to your Todo data structure, as well as some error checking if the request fails.
Also, I do not initialize theTodo variable, hence the use of the ? in the template.
1 Like
And in your app.module.ts you will need to add
import { HttpClientModule } from '@angular/common/http';
and
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [BrowserModule, HttpClientModule, IonicModule.forRoot(), AppRoutingModule],
providers: [
StatusBar,
SplashScreen,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
1 Like
Hello @ChrisGriiffith,
I followed your instructions but I receive absolutely nothing (no status, no body…etc…) while when I use HTTP I receive the data but like @aligassan I can not read data.children.
Can it come from the server?
You need to add observe: 'response'
to your GET API options