简体   繁体   English

使用 environment.ts 运行 ng 测试时出现 Angular 未定义错误

[英]Angular undefined error while running ng test with environment.ts

I have environment.ts in project to set env data from kubernate yaml.我在项目中有 environment.ts 来设置来自 kubernate yaml 的环境数据。

export const environment = {
  PROD_URL: window["env"].prodUrl || 'http://localhost:8080/v1/'
};

While running ng test, I am getting below error.运行 ng test 时,出现以下错误。

An error was thrown in afterAll
  Uncaught TypeError: Cannot read property 'prodUrl ' of undefined
  TypeError: Cannot read property 'prodUrl ' of undefined
      at Module.AytR (http://localhost:9876/_karma_webpack_/webpack:/src/environments/environment.ts:9:30)

window["env"] can be null / undefined . window["env"]可以是null / undefined For that case just use optional chaining .对于这种情况,只需使用optional chaining

export const environment = {
  PROD_URL: window["env"]?.prodUrl || 'http://localhost:8080/v1/'
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM