(十三)、Angular4.0 中间人模式(组件间通讯)

一、在第十二篇博客的demo3项目上改造

二、新建order组件

ng g component order

三、思路:

  • 在price-quote组件中每秒刷新股价数据,点击一个button按钮后,把当前股价发送出去(emit),price-quote的父组件app接收数据,并把数据赋值给自己的属性priceQuote(一个PriceQuote对象),order接收app的输入属性priceQuote,把该属性保存到自己的priceQuote属性中,在order的html中展示出来。


四、在price-quote.component.html中添加'购买股票'的按钮

<div>
  <input type="button" value="购买股票" (click)="buyStock()">
</div>

五、在price-quote.component.ts中定义buyStock函数,发射数据

import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';

@Component({
  selector: 'app-price-quote',
  templateUrl: './price-quote.component.html',
  styleUrls: ['./price-quote.component.css']
})
export class PriceQuoteComponent implements OnInit {

  stockCode = 'IBM';

  price: number;

  // @Output()
  // priceChange: EventEmitter<PriceQuote> = new EventEmitter<PriceQuote>();

  @Output()
  buy: EventEmitter<PriceQuote> = new EventEmitter<PriceQuote>();

  constructor() {
    // 每秒用随机数刷新股价
    setInterval(() => {
      const priceQuote: PriceQuote = new PriceQuote(this.stockCode, 100 * Math.random());
      this.price = priceQuote.lastPrice;

      // // 把每秒产生的新数据发送到外部
      // this.priceChange.emit(priceQuote);
    }, 1000);
  }

  buyStock() {
    this.buy.emit(new PriceQuote(this.stockCode, this.price));
  }

  ngOnInit() {
  }

}

export class PriceQuote {
  constructor(public stockCode: string,
              public lastPrice: number) {

  }
}

六、在app.component.html中通过buyHandler函数接收数据,并把数据输入到order组件中

<app-price-quote (buy)="buyHandler($event)"></app-price-quote>
<app-order [priceQuote]="priceQuote"></app-order>

七、app.component.ts

export class AppComponent {
  // stock = '';
  priceQuote: PriceQuote = new PriceQuote('', 0);

  buyHandler(event: PriceQuote) {
    this.priceQuote = event;
  }
}

八、order.component.ts中接收输入属性

export class OrderComponent implements OnInit {

  @Input()
  priceQuote: PriceQuote;

  ngOnInit() {
  }

}

九、order.component.html展示点击按钮时获取的数据

扫描二维码关注公众号,回复: 3871478 查看本文章
<div>
  买入{{priceQuote.stockCode}}股票,买入价格是{{priceQuote.lastPrice | number:'2.2-2'}}
</div>

十、启动项目,访问localhost:4200

猜你喜欢

转载自blog.csdn.net/zekeTao/article/details/79791259
今日推荐