如何重构我的if / else部分方法,以避免重复代码?

时间:2017-11-06 16:20:21

标签: angular typescript

我在方法中有IF和Else条件,在这两种情况下我都需要调用:“this.replaceSelectedText(link);”。 Qustion是:“我如何通过只调用一次这个来解决这个问题.replaceSelectedText(link);?
这是方法的一部分,应该重构。这个代码在两个地方调用。

`
   // save data for text editor link
    else {
      let link = "";
      let pcTags = this.hyperlinkData.tags ?       
      tags='${this.hyperlinkData.tags}'` : "";
        if(this.isHyperlink) {
          let target = this.selectedTargets.currentWindow;
           if(this.hyperlinkData.target && this.hyperlinkData.target !== 
             this. targets[0]) {
             target = this.selectedTargets.newWindow;
        }
        link = `<a href='${this.hyperlinkData.url ? this.hyperlinkData.url: ""}' target='${target}' title='${this.hyperlinkData.tooltip ? this.hyperlinkData.tooltip : ""}' ${pcTags}>${this.hyperlinkData.linkText}</a>`;
        this.replaceSelectedText(link);
      }
      else {
        link = `<a href='mailto:${this.mailToLinkData.address ? this.mailToLinkData.address : ""}?Subject=${this.mailToLinkData.subject ? this.mailToLinkData.subject : ""}' ${pcTags}>${this.mailToLinkData.linkText}</a>`;
        this.replaceSelectedText(link);
      }
}
`

Here is Screenshot of under method and part of code about I am talking.

1 个答案:

答案 0 :(得分:1)

你能不能这样做,

// save data for text editor link
        else {
          let link = "";
          let pcTags = this.hyperlinkData.tags ?       
          tags='${this.hyperlinkData.tags}'` : "";
            if(this.isHyperlink) {
              let target = this.selectedTargets.currentWindow;
               if(this.hyperlinkData.target && this.hyperlinkData.target !== 
                 this. targets[0]) {
                 target = this.selectedTargets.newWindow;
            }
            link = `<a href='${this.hyperlinkData.url ? this.hyperlinkData.url: ""}' target='${target}' title='${this.hyperlinkData.tooltip ? this.hyperlinkData.tooltip : ""}' ${pcTags}>${this.hyperlinkData.linkText}</a>`;
          }
          else {
            link = `<a href='mailto:${this.mailToLinkData.address ? this.mailToLinkData.address : ""}?Subject=${this.mailToLinkData.subject ? this.mailToLinkData.subject : ""}' ${pcTags}>${this.mailToLinkData.linkText}</a>`;
          }
     this.replaceSelectedText(link);
    }