10.《Angular中间人模式》
2018-07-15 本文已影响0人
笨蛋小明
一、我们要实现的效果
效果图.png1是根组件,当组件7想把消息传递给组件8时,我们这时就需要中间人组件3
如果你已经看了我的上一篇博客《Angular输入输出属性》这篇文章会更好理解,没有的话也完全ok
二、代码示例
新建2个组件product、price
ng g product
ng g price
1.price组件
//price.component.html
<div style="border-top: 1px solid #000">
<h2>这里是价格组件</h2>
<div>
商品id:{{id}}
商品价格:{{price|number:'2.2-2'}}
</div>
<button (click)="buyNow($event)">立即购买</button>
</div>
//price.component.ts
import {Component, EventEmitter, OnInit, Output} from '@angular/core';
@Component({
selector: 'app-price',
templateUrl: './price.component.html',
styleUrls: ['./price.component.css']
})
export class PriceComponent implements OnInit {
id: string = 'product1';
price: number;
@Output()
buy: EventEmitter<PriceRandom> = new EventEmitter();
//EventEmitter后面的<PriceRandom>这个范型代表的是发射出去值的类型,这里是PriceRandom
constructor() {
setInterval(() => {
let priceRandom: PriceRandom = new PriceRandom(this.id, 100 * Math.random());
this.price = priceRandom.lastPrice;
}, 2000);
}
ngOnInit() {
}
buyNow(event) {
this.buy.emit(new PriceRandom(this.id, this.price));
}
}
export class PriceRandom {
constructor(public id: string,
public lastPrice: number) {
}
}
2.根组件(中间人)
//app.component.html
<h1>
我是主组件
</h1>
<!--价格组件 start-->
<app-price (buy)="buyHandle($event)"></app-price>
<!--价格组件 end-->
<!--订单组件 start-->
<app-order [nowPrice]="price"></app-order>
<!--订单组件 end-->
//app.component.ts
import {Component} from '@angular/core';
import {PriceRandom} from './price/price.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
price: PriceRandom = new PriceRandom('', 0);
buyHandle(event: PriceRandom) {
this.price = event;
}
}
3.order组件
//order.component.html
<h2>
我是订单组件
</h2>
<h4>
点击购买时的商品价格为:{{nowPrice.lastPrice}}
</h4>
//order.component.ts
import {Component, Input, OnInit} from '@angular/core';
import {PriceRandom} from '../price/price.component';
@Component({
selector: 'app-order',
templateUrl: './order.component.html',
styleUrls: ['./order.component.css']
})
export class OrderComponent implements OnInit {
@Input()
nowPrice: PriceRandom;
constructor() {
}
ngOnInit() {
}
}
4.效果
当点击price组件的“立即购买”按钮时,order组件会显示点击时的价格