简体   繁体   English

Angular 2+ NgOnInit 为输入数组赋值但抛出未定义的错误

[英]Angular 2+ NgOnInit assigning value to input array but throws an error of undefined

I have a component which expects some inputs, the input that i care about is the feedList.我有一个需要一些输入的组件,我关心的输入是 feedList。 In the feedList there are feed objects with their own data filled in. However, depending on the feed sometimes some data are not provided when the object is created, hence the undefined.在 feedList 中有填充了自己数据的 feed 对象。但是,根据 feed 有时在创建 object 时不提供某些数据,因此未定义。

My problem is that in my HTML i have an ngFor and display the feeds.我的问题是在我的 HTML 我有一个 ngFor 并显示提要。 But some of the feeds for instance, they don't have the但是例如某些提要,它们没有

feed.thirdColumn.kIcon.extraClass

defined, hence when the component renders it will complain about undefined.已定义,因此当组件呈现时它会抱怨未定义。 Here is the complete HTML这是完整的 HTML

<ng-container *ngIf="feedList">
    <div class="container">
        <div class="row feed-container" *ngFor="let feedItem of feedList">
            <div class="kendo-tooltip" kendoTooltip [title]="feedItem.tooltipText" showOn="{{feedItem.tolltipVisible}}">
            <div class="feed-item">
                <div class="col-sm-4 column-inlineBlock feed-avatar">
                    <span>
                        <k-icon [icon]=" { type: 'image', src: '000004.png', extraClass: 'feed-icon'}"></k-icon>
                    </span>
                </div>
                <div class="col-sm-7 column-inlineBlock main-feed-content" (click)="onClickSecondColumn(feedItem)">
                    <div class="title"><strong>{{feedItem.secondColumn.title}}</strong></div>
                    <div class="description">{{feedItem.secondColumn.description}}</div>
                    <div class="footer" *ngIf="!feedItem.secondColumn.footer.isTimeAgo">{{feedItem.secondColumn.footer.value}}</div>
                    <div class="footer time-ago" *ngIf="feedItem.secondColumn.footer.isTimeAgo">
                        <k-icon [icon]="{type: feedItem.secondColumn.footer.icon.type, name: feedItem.secondColumn.footer.icon.name, extraClass: ['icon-clock' +  feedItem.secondColumn.footer.icon.extraClass]}"></k-icon>
                        {{ feedItem.secondColumn.value | timeAgo }}
                    </div>
                </div>
                <div class="col-sm-1 column-inlineBlock third-col" *ngIf="!isTwoColumn" (click)="onClickThirdColumn(feedItem)">
                    <div class="third-col-wrapper">
                        <span class="icon-indicator {{feedItem.thirdColumn.status}}">
                            <k-icon [icon]="{type: feedItem.thirdColumn.kIcon.type, name: feedItem.thirdColumn.kIcon.name, extraClass: ['icon-number' + feedItem.thirdColumn.kIcon.extraClass]}"></k-icon>
                    </span>
                    <span class="number-indicator">
                        <strong id="value-indicator">{{feedItem.thirdColumn.value}}</strong>
                    </span>
                    </div>
                </div>
            </div>
        </div>
        </div>
    </div>
</ng-container>

So all i care about is getting rid of the undefined error from the console.所以我关心的是摆脱控制台中的未定义错误。 What i did so far is this.我到目前为止所做的就是这个。

import { Component, OnInit, ViewEncapsulation, Input, AfterViewInit, HostBinding, OnChanges, SimpleChanges } from '@angular/core';
import { IKFeed } from '../models/k-feed-list.model';
import { KUtilsService as Utils } from 'ng-k-utils';

@Component({
  selector: 'k-feed',
  templateUrl: './ng-k-feed.component.html',
  encapsulation: ViewEncapsulation.None,
})
export class KFeedComponent implements OnInit {

  @Input() isTwoColumn: boolean;
  @Input() feedList: IKFeed[];

  constructor() {
    if (this.feedList)  {
      this.feedList.map(feed => {
        if (feed.thirdColumn.kIcon.extraClass === undefined) {
          console.log('constructor');
        }
      });
    }
   }

  ngOnInit(): void {
    if (Utils.isDefined(this.feedList))  {
      this.feedList.map(feed => {
        if (feed.tooltipText) {
          feed.tolltipVisible = 'hover';
        } else {
          feed.tolltipVisible = 'none';
        }
        if (feed.thirdColumn.kIcon.extraClass === undefined) {
          feed.thirdColumn.kIcon.extraClass = '';
          console.log('ngOnInit');
        }

        if (feed.thirdColumn.kIcon.extraClass === undefined) {
          feed.secondColumn.footer.icon.extraClass = '';
          console.log('ngOnInit');
        }
      });
    }

  }


  public onClickThirdColumn(feedItem: IKFeed) {
    if (Utils.isDefined(feedItem.thirdColumn.actionClickTrigger)) {
      feedItem.thirdColumn.actionClickTrigger();
    }
  }

  public onClickSecondColumn(feedItem: IKFeed) {
    if (Utils.isDefined(feedItem.secondColumn.actionClickTrigger)) {
      feedItem.secondColumn.actionClickTrigger();
    }
  }

}

Which it console logs the ngoninit and sets the values and the HTML is displayed well.它控制台记录 ngoninit 并设置值,并且 HTML 显示良好。 However, i still get the errors in the console log saying that property feed.bla.bla.extraClass is undefined.但是,我仍然在控制台日志中收到错误消息,指出属性 feed.bla.bla.extraClass 未定义。 I tried to use the constructor and check for undefined of extraClass but for some reason when the constructor runs, the feedList(input) is not populated.我尝试使用构造函数并检查未定义的 extraClass 但由于某种原因,当构造函数运行时,未填充 feedList(input)。 What exactly should i do to overcome this problem?我究竟应该怎么做才能克服这个问题?

Have you tried the Elvis operator ?你试过猫王接线员吗?

  • In Typescript it's called optional chaining operator.在 Typescript 中,它被称为可选链接运算符。 Used in the controller of an Angular project.在 Angular 项目的 controller 中使用。

  • In Angular it's called safe navigation operator.在 Angular 中称为安全导航算子。 Used in the template of an Angular project.在 Angular 项目的模板中使用。

In both the cases it can be used like feed?.bla?.bla?.extraClass .在这两种情况下,它都可以像feed?.bla?.bla?.extraClass It makes sure the parent property is defined before trying to access it's children properties.它确保在尝试访问其子属性之前定义父属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM