【问题标题】:How to use forEach loop correctly in angular 2?如何在角度 2 中正确使用 forEach 循环?
【发布时间】:2018-01-23 04:23:42
【问题描述】:

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

【问题讨论】:

  • 问题已经回答但实际上错误实际上是因为您没有初始化角度。

标签: javascript angular foreach angular2-services


【解决方案1】:

正如@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
});

【讨论】:

    【解决方案2】:

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

    使用

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

    【讨论】:

    • 假设viewState.appViewStates是一个数组,也可以使用Array.some
    • 谢谢@Sajeetharan,现在用您的代码替换它后错误已解决,但是当我执行此代码时,我收到 TypeError: Cannot read property 'length' of undefined error : for( let editor of mmEditorTypes){ // mmEditorTypes.forEach(function(editor) { if (!isAppContained(viewState, editor.type)) { this.applicationLifeCycleService.open(editor.type, editor.payload); } }让我知道我是否在这里做错了什么?
    • 我没有看到您在您提供的代码中使用长度的任何地方
    猜你喜欢
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    相关资源
    最近更新 更多