Reputation:
it's the first time that I use Ionic 3 and Angular 5.
I want do a simple call to a rest api, and display the results in a list.
I saw that it's necessary to create a provider, which is responsible to do the calls.
Navigating in google, I saw an example, and my provider is:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
//import 'rxjs/add/operator/map'
/*
Generated class for the PeopleServiceProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
@Injectable()
export class PeopleServiceProvider {
dati : string
constructor(public http: HttpClient) {
console.log('Hello PeopleServiceProvider Provider');
}
load() {
if (this.dati) {
// already loaded data
return Promise.resolve(this.dati);
}
// don't have the data yet
return new Promise(resolve => {
// We're using Angular HTTP provider to request the data,
// then on the response, it'll map the JSON data to a parsed JS object.
// Next, we process the data and resolve the promise with the new data.
this.http.get('https://randomuser.me/api/?results=10')
//.map(res => res.json())
.subscribe(data => {
// we've got back the raw data, now generate the core schedule data
// and save the data for later reference
console.log(data);
this.dati = data["results"];
resolve(this.dati);
});
});
}
}
Then I have my template, and all works fine. My question is more a doubt.
When I get response from api, to take the result I have to do:
data["results"]
I thought that I was able to do:
data.results
Am I miss something? Thanks!
Upvotes: 0
Views: 366
Reputation: 7221
The new HttpClient allow you to use typescript TypeChecking,
so you should create an interface describing your return :
interface MyReturnType {
results: any // <-- i dont know your model
}
...
this.http.get<MyReturnType>('https://randomuser.me/api/?results=10')
.subscribe(data => {
this.dati = data.results;
});
Upvotes: 0