美文网首页
中间人模式和生命周期

中间人模式和生命周期

作者: 2764906e4d3d | 来源:发表于2019-01-25 09:06 被阅读0次

中间人模式

  1. 设计一个购买按钮,获取所需要购买物品的信息,在报价组件中
@Output()
buy:EventEmitter<PriceQuote> = new EventEmitter();


buyStock(event){
  this.buy.emit(new PriceQuote(this.stockCode,this.price));
}
<div>报价组件</div>
<div>

  <input type="button" value="购买" (click)="buyStock($event)">
</div>
  1. 下单组件
<div>下单组件</div>
<div>买100手{{priceQuote.stockCode}}股票
  价格{{priceQuote.lastPrice | number:'2.2-2'}}
</div>

@Input()
stockCode:string;
priceQuote:PriceQuote;
  1. 主组件中
  buyHandle(event:PriceQuote){
  this.priceQuote = event;
}
<app-price-quote (buy)="buyHandle($event)"></app-price-quote>
<app-order [priceQuote]="priceQuote"></app-order>
  1. 报价组件和订单组件在彼此不知道对方存在的时候,共同完成一个下单的功能,也就是两个平行的有共同的父组件的组件之间的通讯,这就是中间人模式,在两个没有共同父组件的组件之间,这时应该使用一个可注入的服务作为中间人,无论何时,组件被创建这个中间人服务被注入,组件可以订阅这个服务发射的事件流

组件生命周期

  1. 组件的生命周期钩子,组件初始化

ngOnChanges
ngDoCheck
ngAfterContentChecked
ngAfterViewChecked

  • (只调用一次)

constructor
ngOnInit
ngAfterContentInit
ngAfterViewInit

  1. 变化检测(变更检测方法就是初始化中会重复执行的方法)

ngOnChanges
ngDoCheck
ngAfterContentChecked
ngAfterViewChecked

3.组件销毁(只调用一次)

ngOnDestroy

  1. 每一个生命周期钩子都是@angular/core中的接口
  2. 生成一个计数器,用来显示每一行日志的编号
let logIndex:number = 1;
  1. 声明一个方法接收msg,将log编号和msg打印出来
logIt(msg:string) {
        console.log('#${{logIndex++}} ${msg}');
    }


  1. 简要调用所有生命周期钩子
import {
  AfterContentChecked,
  AfterContentInit, AfterViewChecked,
  AfterViewInit,
  Component,
  DoCheck,
  Input,
  OnChanges,
  OnDestroy,
  OnInit,
  SimpleChanges
} from '@angular/core';

let logIndex: number = 1;



@Component({
  selector: 'app-life',
  templateUrl: './life.component.html',
  styleUrls: ['./life.component.css']
})

export class LifeComponent implements
  OnInit, OnChanges, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy {


  @Input ()
  name: string ;
  logIt(msg: string) {
    console.log('#${{logIndex++}} ${msg}');
  }

  constructor() {
    this.logIt('name在constructor中的值是:' + name);
  }

  ngOnInit() {
    this.logIt('ngOnInit');

  }
  ngOnChanges(changes: SimpleChanges): void {
    let name = changes['name'].currentValue;
    this.logIt('ngOnChanges:' + name);
  }
  ngAfterContentChecked(): void {
    this.logIt('ngAfterContentChecked');

  }

  ngAfterContentInit(): void {
    this.logIt('ngAfterContentInit');

  }

  ngAfterViewChecked(): void {
    this.logIt('ngAfterViewChecked');
  }

  ngAfterViewInit(): void {
    this.logIt('ngAfterViewInit');
  }

  ngDoCheck(): void {
    this.logIt('ngDoCheck');
  }



  ngOnDestroy(): void {
    this.logIt('ngOnDestroy');
  }

}
<app-life [name]="title"></app-life>
生命周期钩子的调用顺序

相关文章

网友评论

      本文标题:中间人模式和生命周期

      本文链接:https://www.haomeiwen.com/subject/ukapjqtx.html