Uncaught (in promise): Response with status: 0 for

2019-08-22 13:22发布

问题:

I am trying to use the ionic framework and parse json from an API I created, then populate the html in my ionic app with it. When I go to my all-patients page I get the following error:

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

My 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);
       });
  });
}
}

When I go to the page that the error is on it crashes altogether, but nothing is printed out in the console. I am unsure if this is an error with the parsing of the data in the API or something else. I have go to the page for the api manually and the data shows up as expected.

回答1:

I guess that obsidian age already gave you the possible core issue, but nevertheless you should handle promises rejection no matter what. So in that case you should change your code accordingly:

My 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();
...

Hopefully this clarifies the actual error that you reported but also give you more insight on what is going on as you won't be loosing any important information about the error(s).