中间人模式

应用场景:搜索组件,购物车组件,主组件充当中间人

(1)股票搜索组件中,发射一个EventEmitter 类型的事件addCart,并将股票信息也发射出去

import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
@Component({
  selector: 'app-search-stock',
  templateUrl: './search-stock.component.html',
  styleUrls: ['./search-stock.component.css']
})
export class SearchStockComponent implements OnInit {
  @Input()
  private keyword:string;
  private price :number;

  @Output()    //searchResult属性是输出属性,输出的是一个事件,事件的类型为EventEmitter
  searchResult:EventEmitter<StockInfo>=new EventEmitter();
  @Output()
  addCart:EventEmitter<StockInfo>=new EventEmitter();
  constructor() { }

  ngOnInit() {
    setInterval(()=>{
       let stockInfo:StockInfo=new StockInfo(this.keyword,Math.random()*100);
       this.price=stockInfo.price;
       this.searchResult.emit(stockInfo);
    },3000)
  }
  buyStock(){
     this.addCart.emit(new StockInfo(this.keyword,this.price))
  }
}
export class StockInfo{
constructor(public name:string,public price:number){}
}

(2)中间人组件,在主组件中捕获股票搜索组件发射的事件和信息,然后将拿到的信息再传给购物车组件

<input [(ngModel)]="search" />
<app-search-stock [keyword]="search" (addCart)="addcartHandler($event)"></app-search-stock>
<app-cart [stockInfo]="stockInfo"></app-cart>
在控制器

export class AppComponent {
   public stockInfo:StockInfo;
    addcartHandler(StockInfo){
         this.stockInfo=StockInfo;
    }
}
(3)购物车组件,接收从父组件传递过来的股票信息

import { Component, OnInit, Input } from '@angular/core';
import { StockInfo } from '../search-stock/search-stock.component';

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

  constructor() { }
  //购物车组件通过stockInfo这个输入属性,来知道要购买的股票信息
  @Input() private stockInfo:StockInfo;
  ngOnInit() {
  }

}

模板:

<p>
  我是购物车
  要购买的股票是{{stockInfo.name}},价格是{{stockInfo.price}}
</p>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值