【问题标题】:window is not defined Angular Universal 10窗口未定义Angular Universal 10
【发布时间】:2020-08-19 08:46:11
【问题描述】:

我正在开发 Angular 10 应用程序,在实现 SSR 后出现以下错误

/Users/a1410978/Desktop/ssr-workspace/asfc-shell/dist/server/main.js:260991
const _window = window ? window : {};
                ^

ReferenceError: window is not defined
    at Module.../asfc-shared/src/lib/tagging/mi.values.ts (/Users/a1410978/Desktop/ssr-workspace/asfc-shell/dist/server/main.js:260991:17)

mi.values.ts

const _window = window as any ? window as any : {};
const cid_global = _window['cid_global'] ? _window['cid_global'] : {brand: 'unknown', locale: {country: '', language: ''}, ENV: '' };
const z_application = cid_global.accessPath && cid_global.accessPath.slice(1,cid_global.accessPath.length-1);
const z_host = cid_global['brand'].toUpperCase();
const z_country = cid_global.locale.country;
const z_language = cid_global.locale.language;
const contrastPreference = cid_global.contrastPreference;
const z_converged = 'BW';
const z_env = cid_global.ENV;
let lastPageTitle = 'unknown';

/* istanbul ignore next */
export const analyticsDefinitions = {
  /**
   *  Event tagging general
   ********************************************************/
  'onclick': {
    'dl': 'userevent',
    'z_event': 'clicked',
    'z_application': z_application,
    'z_host': z_host,
    'z_country': z_country,
    'z_language': z_language,
    'z_converged': z_converged,
    'z_env': z_env,
    'z_client_id': maskClientId(getCidConfigParams('clientId')),
    'z_referer': getCidConfigParams('source'),
    'z_redir': getCidConfigParams('redirectUri'),
    'z_login': 0
  },

我知道,使用isPlatformBrowser 可以解决我的问题,但我知道如何在常量文件中使用它。

请指导我

【问题讨论】:

标签: javascript angular typescript angular-universal


【解决方案1】:

或者您也可以以正确的方式使用该检查:

// Consider as client side
const isClient = typeof window !== 'undefined';

let cid_global;

if (isClient) {
  // You will write your client initialization here, so you don't have check window anymore
  cid_global = window['cid_global'] : {brand: 'unknown', locale: {country: '', language: ''}, ENV: '' };

  // More to come
}

【讨论】:

  • 现在我收到此错误const cid_global = typeof _window['cid_global'] !== 'undefined' ? _window['cid_global'] : { brand: 'unknown', locale: { country: '', language: '' }, ENV: '' }; ^ TypeError: Cannot read property 'cid_global' of undefined
  • 没有。我将更新答案以帮助您清楚您将在浏览器和服务器中进行哪些工作
  • 但我在if 语句中添加了export const analyticsDefinitions = { dosn;'t work it throws error
  • 看起来您必须为 2 个面返回 2 个不同的值。你应该照顾好自己,因为我不知道你的业务逻辑。
猜你喜欢
  • 2020-11-12
  • 2020-05-28
  • 2020-09-16
  • 1970-01-01
  • 1970-01-01
  • 2016-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多