Javascript 如何在角度 2 中正确使用 forEach 循环?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48394207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:05:44  来源:igfitidea点击:

How to use forEach loop correctly in angular 2?

javascriptangularforeachangular2-services

提问by Vivek

I am new to Angular2 and here I am trying to loop through the array "mmEditorTypes" and checking the condition, if the condition is satisfied then I'll be executing the "open method".

我是 Angular2 的新手,在这里我试图遍历数组“mmEditorTypes”并检查条件,如果条件满足,那么我将执行“open 方法”。

But whenever i execute the below code, I am getting this error :

但是每当我执行以下代码时,我都会收到此错误:

portalModeService: loading of portalMode threw exception:

portalModeService:加载 portalMode 引发异常:

TypeError: Cannot read property 'forEach' of undefined".

类型错误:无法读取未定义的属性“forEach”。

Could someone let me know how to fix this error?

有人可以让我知道如何解决此错误吗?

porta.service.ts :

porta.service.ts :

function isAppContained(viewState, appType){
      let angular:any;
      let isContained = false;
      angular.forEach(viewState.appViewStates, function (appViewState) {
        if (appViewState.signature.appType === appType) {
          isContained = true;
        }
      });
      return isContained;
    }

回答by Javascript Hupp Technologies

As @Sajeetharan said you can't use angular.forEach in angular 2+

正如@Sajeetharan 所说,你不能在 angular 2+ 中使用 angular.forEach

So you can use simple foreach in typescript like :

因此,您可以在打字稿中使用简单的 foreach,例如:

var someArray = [1, 2, 3];
someArray.forEach((item, index) => {
  console.log(item); // 1, 2, 3
  console.log(index); // 0, 1, 2
});

回答by Sajeetharan

You cannot use angular.forEachwith angular, its with angularjs.

您不能使用angular.forEachwith angular,它与 angularjs 一起使用。

use

for (let appViewState of viewState.appViewStates) {
   if (appViewState.signature.appType === appType) {
          isContained = true;
    }
}