这是我的问题:
我有这个端点(GET),它为我提供了一个JSON对象:
'本地主机:3305 / v1 /患者'
我将Ionic 3与提供程序“ RestProvider”一起使用。
我的rest.js看起来像这样:
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>
问题:没有错误,但是视图中没有任何显示。 console.log(data); rest.js的内容显示:[object Object]。
有人知道错误在哪里吗? 谢谢!
答案 0 :(得分:1)
需要通过以下方式重写getPatients()
代码:
getPatients() {
return this.http.get(this.apiUrl+'/patients', {
headers: new HttpHeaders().set('Content-Type', 'application/json'),
})
.toPromise()
}
并在home.ts
getPatients() {
this.restProvider.getPatients().then((res => {
this.patients = data;
}, (err) => {
console.log("rejected");
})
}
答案 1 :(得分:0)
由于您使用的是现代Angular,因此应根据docs使用http方法:
为您服务:
getPatients() {
return this.http.get(this.apiUrl+'/patients')
}
在您的组件中:
getPatients() {
this.restProvider.getPatients()
.subscribe(data => {
this.patients = data;
console.log(this.patients);
});
}
基本上利用评论中指出的可观察对象
答案 2 :(得分:0)
不要忘记像这样或您喜欢的方式来解析json的响应。
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);
});
});
}