Reputation: 109
here's my issue:
I have this endpoint (GET) which gives me a JSON object as a result:
'localhost:3305/v1/patients'
I use Ionic 3 with the provider 'RestProvider'.
My rest.js looks like this:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
@Injectable()
export class RestProvider {
apiUrl = 'localhost:3305/v1';
constructor(public http: HttpClient) {
console.log('Hello RestProvider Provider');
}
getPatients() {
return new Promise(resolve => {
this.http.get(this.apiUrl+'/patients').subscribe(data => {
resolve(data);
console.log(data);
}, err => {
console.log(err);
});
});
}
}
home.ts:
import { Component } from '@angular/core';
import { RestProvider } from '../../providers/rest/rest';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
patients: any;
constructor (public restProvider: RestProvider) {
this.getPatients();
}
getPatients() {
this.restProvider.getPatients()
.then(data => {
this.patients = data;
console.log(this.patients);
});
}
}
home.html:
<ion-content>
<ion-navbar>
<ion-title>My patients</ion-title>
</ion-navbar>
<ion-list>
<ion-list-header>My patients</ion-list-header>
</ion-list>
<ion-list inset>
<ion-item *ngFor="let patient of patients">
<p>{{patient}}</p>
</ion-item>
</ion-list>
</ion-content>
Problem: There's no error, but there's nothing shown in the view. console.log(data); of rest.js shows: [object Object].
Does anyone know where the mistake is? Thanks in regard!
Upvotes: 0
Views: 1063
Reputation: 209
Don't forget to parse te response from the json, like this way, or the way you prefer.
getPatients() {
return new Promise((resolve, reject) => {
this.http.get(`${this.apiUrl}/patients`).subscribe(data => {
try {
response = response.json();
resolve(response);
} catch (error) {
console.log('[api-153]', response);
reject(response);
}
console.log(data);
resolve(data);
}, err => {
console.log(err);
});
});
}
Upvotes: 0
Reputation: 2007
Need to rewrite getPatients()
code in following way:
getPatients() {
return this.http.get(this.apiUrl+'/patients', {
headers: new HttpHeaders().set('Content-Type', 'application/json'),
})
.toPromise()
}
And Getting data in home.ts
getPatients() {
this.restProvider.getPatients().then((res => {
this.patients = data;
}, (err) => {
console.log("rejected");
})
}
Upvotes: 1
Reputation: 9235
Since you are using modern Angular you should use http methods in accordance with docs:
In your service:
getPatients() {
return this.http.get(this.apiUrl+'/patients')
}
In your component:
getPatients() {
this.restProvider.getPatients()
.subscribe(data => {
this.patients = data;
console.log(this.patients);
});
}
Basically leverage observables as pointed out in comments
Upvotes: 0