[英]Angular - How to minimise same code usage?
我不確定如何更好地處理和更改以下實現。
我有兩種訂閱方法,可以重新分配如下值。
public patientLastStatus = "";
this.treatmentStageOne.subscribe(resp => {
if (resp) {
this.patientLastStatus = "Passed";
}
});
this.treatmentStageTwo.subscribe(resp => {
if (resp) {
this.patientLastStatus = "Still in Observation";
}
});
我明白了,以上是完全不同的兩種訂閱方式。 在這里, this.patientLastStatus
的值只是重新賦值。 但我不明白在什么基礎上 Sonarqube 向我展示了更新或重構這個 function 以便它的實現不會重復第 88 行上的那個。
如何以更好的方式改變它?
非常感謝
感謝大家。
您可以將此邏輯提取到更高階的 function 中,它接受新的分配值:
const conditionalChange = newValue =>
resp => {
if (resp) {
this.patientLastStatus = newValue;
}
}
現在您可以在兩個訂閱中重復使用它而無需復制代碼:
this.treatmentStageOne.subscribe(conditionalChange("Passed"));
this.treatmentStageTwo.subscribe(conditionalChange("Still in Observation"));
Sonarqube 正在拋出警告,因為它看到重復。嘗試通過方法更新this.patientLastStatus
。
public patientLastStatus = "";
public updatePateintStatus = (status)=>{
this.patientLastStatus = status;
}
this.treatmentStageOne.subscribe(resp => {
if (resp) {
this.updatePateintStatus("Passed");
}
});
this.treatmentStageTwo.subscribe(resp => {
if (resp) {
this.updatePateintStatus("Still in observations...");
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.