Yin Yin - 6 months ago 35
JSON Question

Ionic2/Angular2 : Error displaying JSON response on the query page

I'm building a getUserByEmail informations page. I can have the response, but I am getting an error when I try to add html.

Here is my .html:

<ion-item>
<ion-label>Email:</ion-label>
<ion-input [(ngModel)]="keyword" type="text" value=""></ion-input>
</ion-item>
<button (click)="getCustomerbyEmail()">Get Customer</button>

THIS IS WORKING
<p>
{{response | json}}
</p>
THIS IS NOT WORKING
(...)
<ion-list-header text-center>
Modifier {{response.username}}
</ion-list-header>
(...)


My customer.ts:

import {Page, NavController} from 'ionic-angular';
import {Http} from 'angular2/http';
import {Inject} from 'angular2/core'
import {CustomerService} from './customers.service';

@Page({
templateUrl: 'build/pages/ecommerce/customers/customers.html',
providers: [CustomerService]
})
export class CustomersPage {

response:string;
keyword:string;
results:string [];
allCustomers:boolean = false;
http;

constructor(public nav: NavController, httpService:Http, private customerService:CustomerService) {
this.customerService = customerService;
this.http = httpService;
this.keyword = '';
}

userPressedCancel() {
this.keyword = '';
}

keyHasBeenPressed(e) {
if (e.keyIdentifier === 'Enter') {
this.customerService.getCustomersById(this.keyword)
.subscribe(
response => this.response = response,
error => console.log(error));
}
}

getCustomerbyEmail() {
this.customerService.getCustomersById(this.keyword)
.subscribe(
response => this.response = response,
error => console.log(error));
}
}


And finally my customer.service.ts:

(...)
getCustomersById(id) : Observable<any> {
let headers = new Headers();
return this._http.get(this._url+this.customers+'/email/'+id+this.urlBase, {
headers : headers
}).map(res => res.json().customer);
}
(...)


If I do a getAllCustomers then iterate the *ngFor="#customer of response" it's working as it should.

What am I missing?
Thanks.
Yin

Answer

Use the safe-navigation (Elvis) operator to not get an error when response is not yet set:

  Modifier {{response?.username}}
Comments