中间人模式

image.png

所谓中间人模式,就是两个组件在都不知道对方的条件下能够进行通信,它们通过一个中间人来进行传值,这里的中间人是父组件
场景:我们定义一个下单的组件和一个报价的组件,通过点击立即购买,将报价组件的值传到下单组件去
QuotePirce组件在这个报价里面主要是通过响应式编程将报价发射出去
quote-price.component.html

 <input type="button" value="立即购买" (click)="buyStock($event)">

quote-price.component.ts

@Output()   //发射东西出去
  lastPrice:EventEmitter<PriceQuote> = new EventEmitter(); //准备用它来发射事件
  @Output()
  buy:EventEmitter<PriceQuote> = new EventEmitter();

  constructor() { 
    setInterval(()=>{
      let priceQuote:PriceQuote = new PriceQuote(this.stcokCode,100*Math.random()); //使用随机函数来模拟股票价格的波动,两个参数一个是股票代码,一个是股票价格
       this.price = priceQuote.lastPrice;
       this.lastPrice.emit(priceQuote)
    },1000)
  }
  //把价格发射出去,不管谁去接受
  buyStock(event){
    this.buy.emit(new PriceQuote(this.stcokCode,this.price));
  }
  ngOnInit() {
  }
}
export class PriceQuote{  //PriceQuote是自定义的一个类
  constructor(public stockCode:string,
              public lastPrice:number
            ){

            }}

然后通过中间人来接受,这里的中间人是app组件
app.component.html

<!-- 通过事件绑定从报价组件接受 -->
<app-price-quote (buy)="buyHandler($event)"></app-price-quote> 
<!-- 通过属性绑定送到到订单组件 -->
<app-order [priceQuote]="priceQuote"></app-order>

app.component.ts

export class AppComponent {
  priceQuote:PriceQuote = new PriceQuote("",0);
  //拿到了报价组件发射过来的值;
  buyHandler(event:PriceQuote){
    this.priceQuote = event;
  }
}

然后在下单组件里面order.component.ts

 @Input()
   priceQuote:PriceQuote;

最后在order.component.html里面定义

<div>
 买100手{{priceQuote.stockCode}}手股票,买入价格是{{priceQuote.lastPrice|number:'2.2-2'}}
</div>
最终效果.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容