Angular2:需要实例化类以防止发现Promise / Property错误

时间:2016-06-27 00:57:37

标签: typescript angular promise

如果我不这样做,在我的“出口课程”中:

purchase = new Purchase();

在我的构造函数之前,然后我得到一个Promise错误,找不到“name”。

我的HTML模板确实与班级绑定:

<h2 text-center><input [(ngModel)]="purchase.name"></h2>

但我希望这个类由构造函数中的Service Injector提供。现在我必须告诉我的细节控制器关于“购买”类的结构,我可能在单元测试时遇到问题。

任何想法如何避免“购买=新购买()”?

这是完整的代码:

import {Component, OnInit} from "@angular/core";
import {PurchaseService} from '../../services/purchase.service';
import {Purchase} from '../../services/purchase';

@Component({
  templateUrl: 'build/pages/detail/detail.html',
  providers: [PurchaseService] // teach injector how to make a PurchaseService
})

export class DetailPage implements OnInit{

  name: String;
  purchase = new Purchase();

  constructor(
    private _navController: NavController, 
    private _navParams: NavParams, 
    private purchaseService: PurchaseService) {

      this._navController = _navController;
      this.name = _navParams.get('name');
  }

  ngOnInit() {
    this.getOnePurchase();
  }

  getOnePurchase() {
    this.purchaseService.getOnePurchase(name)
        .then(result => this.purchase = result
        )
        .then(result => console.log(result)
        )
  }

  pushPage(name: string) {
    this._navController.pop();
  }
}

1 个答案:

答案 0 :(得分:1)

删除new Purchase()并将模板更改为:

<h2 text-center><input [(ngModel)]="purchase?.name"></h2>