首页 > 解决方案 > 为不同的环境使用多个不同的字符串

问题描述

我有来自 https://codecraft.tv/courses/angular/advanced-topics/basic-custom-validators/的代码

function emailDomainValidator(control: FormControl) { (1)
  let email = control.value; (2)
  if (domain !== "domain1.com" && domain != "domain2.com" ){(3)
    let [_, domain] = email.split("@"); (4)
    if (domain !== "codecraft.tv") { (5)
      return {
        emailDomain: {
          parsedDomain: domain
        }
      }
    }
  }
  return null; (6)
}

对于不同的环境,我需要有不同的和多个域(devdomain1、devdomain2、testdomain1、testdomain2 等)。我们是否应该在 app.config 或 environment.ts 中定义这些电子邮件域,以及如何在多个域中使用它的任何示例?

我正在使用 Angular CLI:9.0.5

标签: angulartypescript

解决方案


您可以在环境文件 environment.ts中添加域属性

export const environment = {
  production: false,
  domains: [`devdomain1`, `devdomain2`],
  emailDomain: `codecraft.tv`
}

环境.prod.ts

export const environment = {
  production: false,
  domains: [`proddomain1`, `proddomain2`],
  emailDomain: `codecraft.tv`
}

并在您的验证功能中执行此操作

import { environment } from './environments/environment';  // maybe you will need to correct the path


function emailDomainValidator(control: FormControl) { (1)
  let email = control.value; (2)
  const hasDomain = environment.domains.find(i => {i === domain})
  if (!hasDomain){(3)
    let [_, domain] = email.split("@"); (4)
    if (domain !== environment.emailDomain) { (5)
      return {
        emailDomain: {
          parsedDomain: domain
        }
      }
    }
  }
  return null; (6)
}

推荐阅读