【问题标题】:Angular2: Need to Instantiate Class to prevent Promise / Property not found errorAngular2:需要实例化类以防止 Promise / Property not found 错误
【发布时间】:2016-06-27 12:06:38
【问题描述】:

如果我不这样做,在我的“导出类”中:

purchase = new Purchase();

在我的构造函数之前,我收到一个 Promise 错误,即找不到“名称”。

我的 HTML 模板确实绑定到类:

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

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

任何想法如何避免“purchase = new Purchase()”?

这是完整的代码:

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

【问题讨论】:

    标签: typescript angular promise


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-11
      • 1970-01-01
      • 2015-06-09
      • 1970-01-01
      • 2017-10-30
      • 1970-01-01
      相关资源
      最近更新 更多