【问题标题】:angular universal, d3, ERROR ReferenceError: fetch is not defined角度通用,d3,错误 ReferenceError:未定义提取
【发布时间】:2020-02-04 09:22:15
【问题描述】:

这个problem也出现在角度universal中:

我尝试install node-fetch-polyfill 并导入它。

//npm install node-fetch-polyfill

import * as fetch from "node-fetch-polyfill"; 

ngOnInit() {
    if (typeof fetch !== 'function') {
      (global as any).fetch = fetch;
    }
}

但是还是不行,我的代码中没有直接使用fetch

【问题讨论】:

  • 文档似乎表明这是与 node.js 一起使用的。你确定它支持 Angular 吗?
  • @DelwynPinto 我不确定,但这是我目前能找到的解决方案。

标签: angular angular-universal


【解决方案1】:

文档说:

一个将 window.fetch 引入 Node.js 的轻量级模块

所以我假设您只想在服务器上使用 fetch,所以您应该检查您是在服务器上还是在客户端上。例如:

if (typeof window !== 'undefined' && typeof fetch !== 'function') {
  (global as any).fetch = fetch;
}

但是!最好使用 PLATFORM_ID!

import { PLATFORM_ID, Inject } from '@angular/core';
import { isPlatformBrowser} from '@angular/common';
export class MyComponent {
    isBrowser: boolean;
    constructor(
        @Inject(PLATFORM_ID) platformId: string) {
            this.isBrowser = isPlatformBrowser(platformId);
    }
    ngOnInit() {
       if (!this.isBrowser && typeof fetch !== 'function') {
        ...
     }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-18
    • 2019-10-08
    相关资源
    最近更新 更多