[英]How to reuse an Angular component injecting different data?
我正在努力如何通過注入不同的數據來重用組件?
我有一個客戶組件,其中包含他的數據和鏈接到該客戶的運輸數據。 我希望按鈕批准客戶和運輸數據。
我有一個dialogcomponent,其中有一個用於注入客戶數據的表單。 我正在努力重用該組件,但要注入運輸數據。
我的客戶組件html包含一個批准客戶的按鈕:
<button *ngIf="canCustomerServiceApprove && showSingleCustServiceApprove" mat-raised-button (click)="customerServiceApprove(customer)" color="primary">{{'customers.management.CustomerServiceApproval' | translate}}</button>
這將調用打開對話框組件的方法:
private customerServiceApprove(customer?: Customer) {
this.sourceCustomer = customer;
let dialogRef = this.dialog.open(CustomerServiceApprovalDialogComponent,
{
panelClass: 'mat-dialog-lg',
data: { customer: customer }
});
}
再往下走,我有一個貨運清單,帶有自己的按鈕來批准貨運:
<mat-cell *matCellDef="let shipping" fxFlex="140px">
<button *ngIf="canCustomerServiceApprove" mat-icon-button matTooltip="{{'shippings.management.CustServApprove' | translate}}" (click)="CustServApproval(shipping)"><mat-icon>gavel</mat-icon>
</button>
</mat-cell>
現在,該按鈕具有單獨的方法:
private CustServApproval(shipping?: Shipping) {
this.sourceShipping = shipping;
alert("should open the approvaldialog for shipping id: " + this.sourceShipping.id);
}
dialogcomponent使客戶注入,但不能注入運輸數據。 我在shipData上遇到錯誤,這對我來說是正常的,因為他僅獲得客戶而不是運送。
export class CustomerServiceApprovalDialogComponent {
@ViewChild('form')
private form: NgForm;
constructor(
public dialogRef: MatDialogRef<CustomerServiceApprovalDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: { customer: Customer },
// @Inject(MAT_DIALOG_DATA) public shipData: { shipping: Shipping },
dialogcomponent html文件包含帶有保存按鈕的表單。 我想顯示一個標題,取決於客戶,運輸或保存時用客戶ID或運輸ID保存。
現在,我有一個批准按鈕,可根據customerId保存它:
<button mat-raised-button (click)="save(1, data.customer.id )" color="primary">Approve</button>
所以我不知道如何根據組件接收的內容來注入數據,以及如何根據所接收的數據來獲取保存按鈕,如下所示:
`<button *ngIf="if customer; then type=1 id=customerid else type=2 id=shippingid mat-raised-button (click)="save(type, id )" color="primary">Approve</button>`
我希望清楚嗎?
我在上一個項目中對某些組件使用了發布/訂閱設計模式。 由於它非常通用,因此不確定是否可以為您提供幫助。 但是,如果您只是創建,遵循和實施架構,那么您應該很好。 需要注意的是,實際上,您可以使用flux / redux / mobx模式執行相同的操作
在Angular組件的ngInit()生命周期方法中,您可以使用如下通用訂閱方法:
在構造函數中調用消息傳遞服務:
constructor(private appMessagingService: AppMessaging) { }
ngOnInit()生命周期方法
ngOnInit() {
this.sub = this.appMessagingService.getComp1Message()
.takeWhile(() => this.alive) //alive is just a boolean variable
.subscribe(message => {
this.message = message;
});
}
不要忘記在ngDestroy()方法中清理可觀察對象:
ngOnDestroy() {
this.sub.unsubscribe();
this.alive = false;
}
有一個應用程序范圍的消息傳遞服務,其中包含您的基本發送,獲取和清除消息。
AppMessaging.service.ts:
sendComp1Message(message) {
this.message.next(message);
}
getComp1Message(): Observable<any> {
return this.message.asObservable();
}
clearComp1Message() {
this.message.next();
}
巨大的呼喊聲給這個家伙,他擁有一些寶貴的資源,並啟發了我使用這個簡單的解決方案。 簡單是關鍵IMO祝您好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.