中间人模式,子组件获取父组件的数据是一个对象的时候,会在子组件中报取不到这个对象里面参数的错误,即使在子组件将该对象设置了默认参数也不行

来源:6-4 中间人模式

TAO511

2017-08-02


写回答

3回答

TAO511

提问者

2017-08-04

我表述可能不太准确,中间人也涉及到父子组件的数据传递吧(后面我在父组件定义stockInfo的时候,new StockInfo("",0)就解决啦)代码如下

export class AppComponent  {
  private search:String;
  private currentPrice:number;
  private stockInfo:StockInfo;//视频中代码是这个,但是这样导致参数name报undefined
  // private stockInfo:StockInfo = new StockInfo("",0);//这个是我后面初始化就直接定义了空字符串和0就没报错啦
  getSearchResult(stockInfo:StockInfo){
    this.currentPrice = stockInfo.price;
  }
  getBuyStock(stockInfo:StockInfo){
    this.stockInfo = stockInfo;
  }
<p>我是父组件</p>
<input type="text" placeholder="请输入关键字" [(ngModel)]="search">
<!--要搜索的关键字是{{keyWord}},他的价格是{{currentPrice}}-->
<app-stock-search [keyWord]="search"  (buyStock)="getBuyStock($event)"></app-stock-search>
<app-stock-car  [stockInfo]="stockInfo"></app-stock-car>
<p>
  购物车
</p>
<div>
  要购买的股票是{{stockInfo.name}}, 购买价格是{{stockInfo.price}}
</div>

这样写的报错信息:

stock-car.component.html:4 ERROR TypeError: Cannot read property 'name' of undefined    at Object.eval [as updateRenderer] (stock-car.component.html:4)    at Object.debugUpdateRenderer [as updateRenderer] (services.ts:307)    at checkAndUpdateView (view.ts:392)    at callViewAction (view.ts:700)    at execComponentViewsAction (view.ts:644)    at checkAndUpdateView (view.ts:392)    at callViewAction (view.ts:700)    at execComponentViewsAction (view.ts:644)    at checkAndUpdateView (view.ts:392)    at callWithDebugContext (services.ts:645)

5
0

Windy9

2017-08-08

我的也是同样的问题,为什么name会报undefined但price不会?

0
0

JoJo

2017-08-03

中间人模式是在无父子关系的组件间用的,为什么会有父组件和子组件?代码帖出来看下。

0
1
TAO511
我把代码写在回答中去啦
2017-08-04
共1条回复

Angular4.0从入门到实战 打造股票管理网站

Angular新特性,教你熟练使用 Angular 和 Typescript 开发组件式单页应用

2683 学习 · 1361 问题

查看课程