[英]Why can't I return data from an API service in Ionic 4?
I'm upgrading from Ionic 3 to 4 and keep encountering problems with my API services. 我正在从Ionic 3升级到4,并不断遇到我的API服务问题。 In this particular instance I'm trying to retrieve a user's tickets so that I may list them. 在这种特定情况下,我试图检索用户的票证,以便我可以列出它们。
Unfortunately, every time I do this I get the 'whoops' error message, even if the tickets are successfully fetched from the API. 不幸的是,即使每次从API成功获取票证,每次执行此操作都会收到“ whoops”错误消息。 On top of that I can't seem to figure out how to successfully get the tickets returned from the service into my page; 最重要的是,我似乎无法弄清楚如何将服务返回的票证成功地放入我的页面。 I'm currently getting a Cannot read property 'then' of undefined
error. 我目前正在获得Cannot read property 'then' of undefined
错误Cannot read property 'then' of undefined
。
On top of that, the data
is now coming back as data: [object Object],[object Object]
最重要的是, data
现在作为data: [object Object],[object Object]
返回data: [object Object],[object Object]
getSubmittedTickets() {
let body = new FormData();
body.append('username', this.username);
body.append('password', this.password);
this.http
.post(this.apiService.url, body)
.subscribe((data: any) => {
console.log('data: ' + data);
return data;
}, error => {
console.log('whoops');
});
}
ngOnInit() {
this.getSubmittedTickets();
}
getSubmittedTickets() {
this.ticketService.getSubmittedTickets()
.then(data => {
this.tickets = data;
console.log('tickets: '+this.tickets);
});
}
The method name in your service is getTickets()
. 服务中的方法名称为getTickets()
。 But in your TS file, you have used getSubmittedTickets()
. 但是在TS文件中,您使用了getSubmittedTickets()
。
The code in your TS file should be: TS文件中的代码应为:
getSubmittedTickets() {
this.ticketService.getTickets()
.then(data => {
this.tickets = data;
console.log('tickets: '+this.tickets);
});
}
The service should return an Observable 服务应返回一个Observable
getSubmittedTickets() {
let body = new FormData();
body.append('username', this.username);
body.append('password', this.password);
return this.http.post(this.apiService.url, body);
}
and the component calls the method from the service and then subscribe to the returned value 然后组件从服务中调用方法,然后订阅返回的值
getSubmittedTickets() {
this.ticketService.getSubmittedTickets()
.subscribe(data => {
this.tickets = data;
console.log('tickets: '+this.tickets);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.