未捕获(承诺中):响应状态为:0,URL 为:null
2017-11-26
5049
我尝试使用 ionic 框架并从我创建的 API 解析 json,然后用它填充我的 ionic 应用程序中的 html。当我转到我的 all-patients 页面时,我收到以下错误:
Error: Uncaught (in promise): Response with status: 0 for URL: null
at c (http://130.215.45.72:8102/build/polyfills.js:3:19752)
at c (http://130.215.45.72:8102/build/polyfills.js:3:19461)
at http://130.215.45.72:8102/build/polyfills.js:3:20233
我的 all-patients.ts:
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { RestService } from '../../providers/rest-service/rest-service';
@Component({
selector: 'page-all-patients',
templateUrl: 'all-patients.html',
providers: [RestService]
})
export class AllPatientsPage {
public data: any;
constructor(public navCtrl: NavController, public restService: RestService){
this.loadPeople();
}
loadPeople(){
this.restService.load()
.then(data => {
this.data = data;
});
}
}
rest-services.ts:
import { Http } from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
/*
Generated class for the RestServiceProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
@Injectable()
export class RestService {
constructor(public http: Http) {
console.log('Hello RestServiceProvider Provider');
}
load() {
if (this.data) {
// already loaded data
return Promise.resolve(this.data);
}
// don't have the data yet
return new Promise(resolve => {
this.http.get('url')
.map(res => res.json())
.subscribe(data => {
this.data = data.results;
resolve(this.data);
});
});
}
}
当我转到出现错误的页面时,它完全崩溃了,但控制台中没有打印出任何内容。我不确定这是 API 中数据解析错误还是其他原因。我手动转到 api 页面,数据按预期显示。
1个回答
我猜黑曜石时代已经给你提供了可能的核心问题,但无论如何你都应该处理承诺被拒绝的情况。 因此在这种情况下你应该相应地更改你的代码:
我的 all-patients.ts:
...
loadPeople(){
this.restService.load()
.then(data => {
this.data = data;
})
.catch(e => console.error); // change this line according to your debugging/logging needs
}
...
rest-services.ts:
...
import 'rxjs/add/operator/toPromise';
...
return this.http.get('url')
.map(res => res.json())
.subscribe(data => {
this.data = data.results;
return this.data
})
.toPromise();
...
希望这能澄清你报告的实际错误,同时也能让你更深入地了解正在发生的事情,因为你不会丢失有关错误的任何重要信息。
Ricardo Ferreira
2017-11-26