Angular 如何使用Subscribe方法编写角度干净的代码?
如何用Angular编写用于订阅的干净代码?由于Angular Typescript的异步特性,我们必须在代码中的不同位置编写一个Angular 如何使用Subscribe方法编写角度干净的代码?,angular,typescript,rxjs,angular-material,angular8,Angular,Typescript,Rxjs,Angular Material,Angular8,如何用Angular编写用于订阅的干净代码?由于Angular Typescript的异步特性,我们必须在代码中的不同位置编写一个processItems()方法。一个位置没有对话框警告,另一个位置在“订阅”对话框关闭中 有没有办法将代码集中在一个地方 当前: public validateProductOrder(){ if (this.product.cost > 1000){ this.runMaterialDialogBoxWarning(); }
processItems()
方法。一个位置没有对话框警告,另一个位置在“订阅”对话框关闭中
有没有办法将代码集中在一个地方
当前:
public validateProductOrder(){
if (this.product.cost > 1000){
this.runMaterialDialogBoxWarning();
}
else if (this.product.addressType == 'International'){
this.sendConfirmationEmailCode();
this.runMaterialDialogBoxWarning();
}
else{
this.processItems();
}
public processItems(){
this.processOrderForm();
this.deliverShipping();
}
runMaterialDialogBoxWarning(){
materialDialogBoxRef.afterClosed().subscribe(result=> {
if (data.submit == true){
this.processItems(); // this is another location we have to write processItems();
});
public validateProductOrder(){
if (this.product.cost > 1000){
this.runMaterialDialogBoxWarning();
this.processItems();
}
else if (this.product.addressType == 'International'){
this.sendConfirmationEmailCode();
this.runMaterialDialogBoxWarning();
this.processItems();
}
else{
this.processItems();
}
理想方法:
public validateProductOrder(){
if (this.product.cost > 1000){
this.runMaterialDialogBoxWarning();
}
else if (this.product.addressType == 'International'){
this.sendConfirmationEmailCode();
this.runMaterialDialogBoxWarning();
}
else{
this.processItems();
}
public processItems(){
this.processOrderForm();
this.deliverShipping();
}
runMaterialDialogBoxWarning(){
materialDialogBoxRef.afterClosed().subscribe(result=> {
if (data.submit == true){
this.processItems(); // this is another location we have to write processItems();
});
public validateProductOrder(){
if (this.product.cost > 1000){
this.runMaterialDialogBoxWarning();
this.processItems();
}
else if (this.product.addressType == 'International'){
this.sendConfirmationEmailCode();
this.runMaterialDialogBoxWarning();
this.processItems();
}
else{
this.processItems();
}
如果理想的方法不可能,那没关系,只是好奇而已。使用订阅操作可能会使跟踪项目变得困难。您可以尝试创建一个可观察对象,模仿对话框返回的响应,然后在一个位置订阅结果 这样,方法
processItems
将只在一个位置调用。以下是实现这一目标的示例:
import{Observable,of}来自'rxjs';
//代码的其余部分
公共validateProductOrder(){
让obs:可观察;
如果(此产品成本>1000){
obs=this.runMaterialDialogBoxWarning();
}else if(this.product.addressType=='International'){
此.sendConfirmationMailCode();
obs=this.runMaterialDialogBoxWarning();
}否则{
//在此处指定一个可观察到的即时响应。
obs=of({submit:true});
}
//在这里订阅可观察到的。
obs.subscribe(数据=>{
如果(数据提交){
this.processItems();
}
});
}
公共物品({
这个.processOrderForm();
这是一个简单的例子;
}
runMaterialDialogBoxWarning(){
返回materialDialogBoxRef.afterClosed();
}