如何在Angular 2中正确使用forEach循环?

4
我是一位有益的助手,可以为您翻译文本。

我刚接触Angular2,试图循环遍历数组“mmEditorTypes”,并检查条件是否满足,如果满足,则执行“open方法”。

但无论何时执行下面的代码,都会出现以下错误:

portalModeService:加载portalMode时出现异常:

TypeError: 无法读取未定义的“forEach”属性。

请问有人可以告诉我如何解决这个错误吗?

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;
    }

问题已经得到解答,但实际上错误是因为您没有初始化Angular。 - xpioneer
2个回答

11

就像@Sajeetharan所说,你无法在Angular 2+中使用angular.forEach。

因此,你可以在TypeScript中使用简单的foreach,例如:

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

5
您不能使用 angular.forEach,因为它是用于 angularjs 的,而不是 angular
请使用:
for (let appViewState of viewState.appViewStates) {
   if (appViewState.signature.appType === appType) {
          isContained = true;
    }
}

假设 viewState.appViewStates 是一个数组,你也可以使用 Array.some - Rajesh
谢谢@Sajeetharan,使用您的代码替换后现在错误已被解决,但是当我执行此代码时,我会遇到TypeError: Cannot read property 'length' of undefined错误: for(let editor of mmEditorTypes){ // mmEditorTypes.forEach(function(editor) { if (!isAppContained(viewState, editor.type)) { this.applicationLifeCycleService.open(editor.type, editor.payload); } } 请问这里是否有什么地方做错了? - Vivek
我没有看到你在提供的代码中使用长度。 - Sajeetharan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接