比如在订单组件中将支付金额传递给支付组件
order.component.ts
import { Component, OnInit } from '@angular/core';
import { OrderService } from '../services/order.service';
@Component({
selector: 'app-order',
template: `
<router-outlet name="pay"></router-outlet>
`,
styleUrls: ['./order.component.scss']
})
export class OrderComponent implements OnInit {
amount!: number;
constructor(private orderService: OrderService) { }
ngOnInit(): void {
this.orderService.createOrder().subscribe(data => {
this.amount = data.amount;
});
}
}
payment-wechat.component.html
<div class='price-tag'>¥{{ amount }}</div>
尝试了2种方法:
1)router-outlet 的 activate 事件
order.component.html
<router-outlet name="pay" (activate)="onActivate($event)"></router-outlet>
order.component.ts
export class OrderComponent implements OnInit {
order?: Order;
constructor(private orderService: OrderService) { }
ngOnInit(): void {
this.orderService.createOrder().subscribe(order => {
this.order = order;
});
}
onActivate(component: PaymentWechatComponent) {
component.amount = this.order?.amount ?? 88;
}
}
这种方式可以直接更新子组件的属性值,但无法通过 subscribe 更新子组件的属性值,因为 onActivate 执行在先。
参考:Angular : router-outlet and its events
2)EventEmitter 发射事件
order.component.ts
export class OrderComponent implements OnInit {
order?: Order;
@Output()
orderAmount: EventEmitter<number> = new EventEmitter();
constructor(private orderService: OrderService) { }
ngOnInit(): void {
this.orderService.createOrder().subscribe(order => {
this.order = order;
this.orderAmount.emit(order.amount);
});
}
}
但由于采用 router-outlet 加载子组件,无法通过属性将事件发送给子组件。
order.component.html
<router-outlet name="pay"></router-outlet>
在写完补充问题后突然想到,将方法1与方法2结合(router-outlet activate
+ EventEmitter
)就能解决问题。
在 OrderComponent 的 onActivate 方法中 subscribe EventEmitter
export class OrderComponent implements OnInit {
order?: Order;
@Output()
orderAmount: EventEmitter<number> = new EventEmitter();
constructor(private orderService: OrderService) { }
ngOnInit(): void {
this.orderService.createOrder().subscribe(order => {
this.order = order;
this.orderAmount.emit(order.amount);
});
}
onActivate(component: PaymentWechatComponent) {
this.orderAmount.subscribe(amount =>{
component.amount = amount;
});
}
}
修改代码后搞定!
Passing data into "router-outlet" child components
– dudu 1年前