Ionic2 / Angular2:在查询页面上显示JSON响应时出错

时间:2016-05-30 09:56:12

标签: json angular ionic2

我正在构建一个getUserByEmail信息页面。我可以得到回复,但是当我尝试添加html时出现错误。

这是我的.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>
(...)

我的客户:

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

最后是我的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);
  }
(...)

如果我做一个getAllCustomers然后迭代* ngFor =“#customer of response”它正在按预期工作。

我错过了什么? 谢谢。 阴

1 个答案:

答案 0 :(得分:1)

使用safe-navigation(Elvis)运算符在response尚未设置时不会出错:

  Modifier {{response?.username}}