【问题标题】:Angular 8: Object doesn't support property or method 'includes'Angular 8:对象不支持属性或方法“包含”
【发布时间】:2019-12-13 09:03:20
【问题描述】:

我正在 angular8 中构建一个应用程序。我在 angular5/6/7 上工作,对于这些应用程序,我取消了 polyfills.ts 中存在的导入的注释。对于 Angular 8,它只有 3 个导入,即 classlist.js、web-animation-js 和 zone.js/dist/zone。我的应用程序在 IE 中运行良好。但是我开始使用包含函数来查看一个项目是否存在。它在 chrome 中运行良好。在 IE 中它会抛出 Object does not support property or method 'includes' 错误。

【问题讨论】:

标签: angular angular8 angular-cli-v8


【解决方案1】:

在polyfill.js 中添加以下行:

import 'core-js/es7/array';

【讨论】:

  • 为什么,添加这个有什么用?
  • 在 Angular 8 中工作,将 /es7/ 替换为 /es/
  • @JeremyThille,将 /es7/ 和 /es6/ 更改为 /es/ 也适用于 Angular 9,谢谢!
  • @JeremyThille,/es/ 在 Angular 9 中对我不起作用,但 /es7/ 起作用了。
  • @AnandShendage 文件是polyfill.ts 而不是polyfill.js。您可能希望更新答案。
【解决方案2】:

对于 Angular 8+,他们默认添加了差异加载;现代浏览器(如 Chrome 和 FF)将加载与 es2015 兼容的 JS 文件,而旧版浏览器(如 IE11)将加载另一个但功能相同的 es5 JS 文件。

为了将 polyfills 添加到您的 es5 文件中(由 IE11 加载),您需要手动将它们添加到 src/polyfills.ts 文件中。

// Only load the 'includes' polyfill
import 'core-js/features/array/includes';

或者你可以添加所有的 polyfill:

// polyfill all `core-js` features:
import "core-js";

【讨论】:

    【解决方案3】:

    includes 是存在于Array.prototype 和String.prototype 上的函数,IE 不支持。您需要使用如下所示的 polyfill:

    if (!String.prototype.includes) {
      String.prototype.includes = function(search, start) {
        'use strict';
        if (typeof start !== 'number') {
          start = 0;
        }
    
        if (start + search.length > this.length) {
          return false;
        } else {
          return this.indexOf(search, start) !== -1;
        }
      };
    }
    

    或类似的数组。您还可以检查 Core.js 是否有 polyfills

    【讨论】:

      【解决方案4】:

      caniuse 提示 Includes 功能不可用。

      https://caniuse.com/#search=includes

      但以下内容可能会有所帮助。

      摘自这篇文章:https://blog.angularindepth.com/angular-and-internet-explorer-5e59bb6fb4e9

      治愈方法

      要让 IE 正常工作,我们需要执行以下两个步骤:

      取消注释 polyfill.ts 文件中的一些导入。安装几个 npm 包。 Polyfill Imports 首先在你的IDE中打开文件或者文本 编辑器:ie-test\src\polyfills.ts

      取消注释其中的所有导入行。对我来说,简单的方法就是 用 import 替换所有 // import

      之后我的看起来像这样:

      安装 npm 包 注意里面有一些 npm install 命令 厘米。如果您使用的是早期版本的 Angular CLI,则 也可能是第三个。对于 Angular CLI 版本 7、6 和 1.7,您 需要运行:

      npm install --save classlist.js npm install --save web-animations-js 成功 现在在项目的根目录中运行:

      ng 将 Internet Explorer 服务于:http://localhost:4200 和您 将看到您的应用程序正常工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-07
        • 1970-01-01
        • 1970-01-01
        • 2020-06-10
        • 2013-12-28
        • 2019-03-31
        • 2019-07-05
        • 2015-04-14
        相关资源
        最近更新 更多