Unhandled Promise Rejection Warning when trying to initialize a variable with a model

Cordova CLI: 6.5.0
Ionic Framework Version: 2.0.0-rc.4
Ionic CLI Version: 2.2.1
Ionic App Lib Version: 2.2.0
Ionic App Scripts Version: 0.0.47
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Windows 8.1
Node Version: v6.9.2
Xcode version: Not installed

Hi, im new on ionic so i’m going to explain what i’m trying to do. I’m developing a MCV project conected to a remote server. I’m trying to initialize a variable with a type of date from a model called “edificio” and when i try to initialize it like “edificio= new Edificio(0,”","");" the console trows me “UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property ‘content’ of null” but i actually have a similar crud for users and this is working without any trouble. And when i comment that specific line the project works fine with “ionic serve” command.

import { Component } from '@angular/core';
import { NavController, NavParams,ViewController } from 'ionic-angular';

import { Edificio } from '../model/edificio';
import { EdificioService } from './edificio.servicio';
import { EdificioPage } from './edificio';

@Component({
	selector: 'page-crearEdificio',
	templateUrl: 'crearEdificio.html',
	providers: [EdificioService]
})
export class CrearEdificioPage
{
	edificio= new Edificio(0,"","");
	respuesta:any;
	error:any;
	constructor(public navCtrl: NavController, public navParams: NavParams,  private EdificioService: EdificioService,private viewCtrl: ViewController)
	{
		this.respuesta=[];
		this.error='';
	}...

Here is the “model”

export class Edificio
{
	constructor
	(
		idEdificio: number,
		nombreEdificio: string,
		direccionEdificio: string	
		){}
}

I think you’ve oversimplified your code for posting purposes, because the error message mentions a “content” property, but I don’t see anywhere you’re referencing one. Incidentally, I’m 99% certain that you don’t want to be declaring EdificioService in CrearEdificioPage's providers. That will make each component that does that get a different instance of the service.

Thanks for you reply. That’s why I don’t undestand that issue, because I’m not trying to full in anything just initialize an “empty” variable in this way:

edificio= new Edificio(0,"","");

And when I comment that line, the project compile without errors. There are no other variable with same name and I’m not calling a post or get request to the server.

app.module.ts

import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';
import { HttpModule }    from '@angular/http';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';

//servicios
import { UsuarioService } from '../pages/usuario/usuario.servicio';

import { EdificioService } from '../pages/edificio/edificio.servicio';

import { HomePage } from '../pages/home/home';
import { LoginPage } from '../pages/login/login';
import { TabsPage } from '../pages/tabs/tabs';
//Import usuario
import { UsuarioPage } from '../pages/usuario/usuario';
import { CrearUsuarioPage } from '../pages/usuario/crearUsuario';
import { VerUsuarioPage } from '../pages/usuario/verUsuario';
import { EditarUsuarioPage } from '../pages/usuario/editarUsuario';
import { PopUsuarioPage } from '../pages/usuario/popUsuario';
//Import Edificio
import { EdificioPage } from '../pages/edificio/edificio';
import { CrearEdificioPage } from '../pages/edificio/crearEdificio';
/*import { VerEdificioPage } from '../pages/edificio/verEdificio';
import { EditarEdificioPage } from '../pages/edificio/editarEdificio';
import { PopEdificioPage } from '../pages/edificio/popEdificio';*/

@NgModule({
  declarations: [
    MyApp,    
    HomePage,
    LoginPage,
    TabsPage,
    UsuarioPage,
    CrearUsuarioPage,
    VerUsuarioPage,
    EditarUsuarioPage,
    PopUsuarioPage,
    EdificioPage,
    CrearEdificioPage
  ],
  imports: [
    IonicModule.forRoot(MyApp),
    BrowserModule,
    FormsModule,
    HttpModule,
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    LoginPage,
    TabsPage,
    UsuarioPage,
    CrearUsuarioPage,
    VerUsuarioPage,
    EditarUsuarioPage,
    PopUsuarioPage,
    EdificioPage,
    CrearEdificioPage
  ],
  providers: [{provide: ErrorHandler, useClass: IonicErrorHandler},UsuarioService,EdificioService]
})
export class AppModule {}

crearEdificio.ts

import { Component } from '@angular/core';
import { NavController, NavParams,ViewController } from 'ionic-angular';

import { Edificio } from '../model/edificio';
import { EdificioService } from './edificio.servicio';
import { EdificioPage } from './edificio';

@Component({
	selector: 'page-crearEdificio',
	templateUrl: 'crearEdificio.html'
})
export class CrearEdificioPage
{
	edificio= new Edificio(0,"","");
	respuesta:any;
	error:any;
	constructor(public navCtrl: NavController, public navParams: NavParams,  private EdificioService: EdificioService,private viewCtrl: ViewController)
	{
		this.respuesta=[];
		this.error='';
	}	
  	//Esconde el botón back en la barra de navegación
  	ionViewWillEnter()
  	{
  		this.viewCtrl.showBackButton(true);
  	}
  	goBack()
  	{
  		this.navCtrl.pop();
  	}  	
}

edificio.servicio.ts

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Edificio } from '../model/edificio';
import { Observable }     from 'rxjs/Observable';

import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/observable/throw';

@Injectable()
export class EdificioService
{
	private edificioUrl = '';

	constructor (private http: Http) {}

	getEdificios ():Observable<any>
	{		
    this.edificioUrl = 'http://arrenda.api/edificio/getAll';
		return this.http.get(this.edificioUrl)
                    .map(this.extractData)
                    .catch(this.handleError);
  }  
  postCrearEdificio(body: Object):Observable<any>
  {
    this.edificioUrl = 'http://arrenda.api/edificio/createEdificio';
    let headers = new Headers({ 'Content-Type': 'application/json; charset=UTF-8' }); // ... Set content type to JSON
    let options = new RequestOptions({ headers: headers });
    return this.http.post(this.edificioUrl, body, options) // ...using post request
          .map(this.extractData) // ...and calling .json() on the response to return data
          .catch((error:any) => Observable.throw(error));
  }
  postEditarEdificio(body: Object):Observable<any>
  {
    this.edificioUrl = 'http://arrenda.api/edificio/updateEdificio';
    let headers = new Headers({ 'Content-Type': 'application/json; charset=UTF-8' }); // ... Set content type to JSON
    let options = new RequestOptions({ headers: headers });
    return this.http.post(this.edificioUrl, body, options) // ...using post request
          .map(this.extractData) // ...and calling .json() on the response to return data
          .catch((error:any) => Observable.throw(error));
  }
  postEliminarEdificio(body: Object):Observable<any>
  {      
    this.edificioUrl = 'http://arrenda.api/edificio/deleteEdificio';
    let headers = new Headers({ 'Content-Type': 'application/json; charset=UTF-8' }); // ... Set content type to JSON
    let options = new RequestOptions({ headers: headers });
    return this.http.post(this.edificioUrl, body, options) // ...using post request
          .map(this.extractData) // ...and calling .json() on the response to return data
          .catch((error:any) => Observable.throw(error));
  }
  private extractData(res: Response)
  {  	
    let body = res.json();    
    return body;
  }
   
  private handleError (error: Response | any) {
    // In a real world app, we might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }
}

I think there are all the classes related with crearEdificio.ts

It does seem mysterious, but I’m still not seeing anywhere that a “content” property is being referenced. Is it in a template somewhere?

It’s a generic error message from deep inside Ionic, often due to a bad module. For example, it looks as though you have some modules commented out but still declared. You probably need to check every filename and path you use in app.module.ts, for typos, mismatched upper/lower case, etc. Due to stuff like this, I only use autocomplete to define imports. It avoids a lot of hassle.

If you look at your stack trace line by line, it might help. The error message itself probably does not refer to your code at all.

Hi! thanks to y2 for the replies. @AaronSterling had reason, there was a mistake on an import (Edificio instead of edificio), but not in app.module.ts but in edificio.ts from the page (not the model)

import { Component } from '@angular/core';
import { NavController, NavParams,ViewController, PopoverController } from 'ionic-angular';
**import { Edificio } from '../model/Edificio';**
import { EdificioService } from './edificio.servicio';
import { CrearEdificioPage } from './crearEdificio';
import { VerEdificioPage } from './verEdificio';
import { EditarEdificioPage } from './editarEdificio';
import { PopEdificioPage } from './popEdificio';

/*
  Generated class for the Edificio page.

  See http://ionicframework.com/docs/v2/components/#navigation for more info on
  Ionic pages and navigation.
  */
  @Component({
  	selector: 'page-edificio',
  	templateUrl: 'edificio.html'
  })
  export class EdificioPage
  {
    edificios: Edificio[];
    items: string[];
    errorMessage: string;
    mode: 'Observable';
    respuesta:boolean;
    constructor(public navCtrl: NavController, public navParams: NavParams,  private EdificioService: EdificioService,private viewCtrl: ViewController, public popoverCtrl: PopoverController)
    {
      this.edificios=[];
      this.respuesta=navParams.get('respuesta');   
    }

    ionViewDidLoad() {
      console.log('ionViewDidLoad EdificioPage');
    }
    goToCrearEdificio()
    {
      this.navCtrl.push(CrearEdificioPage);
    }
    ionViewWillEnter()
    {
      this.viewCtrl.showBackButton(false);
    } 

  }

Could you tell me: Why this import in edificio.ts affected my code when i was trying to initialize a variable in crearEdificio.ts? I don’t understand because the issue only appears when I called the “edificio model” to initialize.

I don’t know. I might be able to figure it out by reading the Ionic source code, but I never bothered to. I had a similar problem when I was starting out, before I got serious about using a TypeScript IDE. I figured it out by Googling pieces of the error message and reading related GitHub threads. I think I saw @rapropos post that he uses the WebStorm IDE (or a cousin), which has strong TypeScript support, so it’s not surprising he hadn’t seen this personally.

Moral of the story: use a code editor with better TypeScript support, and always use autocomplete features to define paths and module names.

Cousin it is. I started using IntelliJ IDEA back when I was doing lots of Java stuff, and it has excellent support for a ridiculous number of languages, including TypeScript.