Angular 8: 对象不支持 属性 或方法 'includes'

Angular 8: Object doesn't support property or method 'includes'

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

caniuse 提示 Includes 函数不可用。

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

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

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

The Cure

To get IE working there are basically two steps we need to do:

Un-comment some imports in the polyfill.ts file. Install a couple of npm packages. Polyfill Imports First open the file in your IDE or text editor: ie-test\src\polyfills.ts

Un-comment all the import lines in there. For me, the easy way is just to replace all // import with import

After that mine looks like this:

Install npm Pacakages Notice there are some npm install commands in the comments. If you are using an early version of Angular CLI, there may also be a third one. For Angular CLI versions 7, 6, and 1.7 you need to run:

npm install --save classlist.js npm install --save web-animations-js Success Now in the root of your project just run:

ng serve Point Internet Explorer at: http://localhost:4200 and you will see your application working.

includesArray.prototype and 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

polyfill.js 中添加以下行:

import 'core-js/es7/array';

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

为了将 polyfill 添加到您的 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";