无法读取未定义的属性“ commitment_id”

时间:2018-10-09 10:43:05

标签: angular

我有一个在这样的路由commitments/:id上打开的页面。 我想按ID显示属于该特定页面的报告的日期。但是我收到一条消息,指出无法读取属性“ commitment_id”:

  

错误TypeError:无法读取未定义的属性'commitment_id'

     

评估时(commitment.component.ts:88)

     

在Array.filter()

     

在SafeSubscriber.eval [作为_next](commitment.component.ts:87)

     

在SafeSubscriber .__ tryOrUnsub(Subscriber.js:239)

     

在SafeSubscriber.next(Subscriber.js:186)

     

在Subscriber._next(Subscriber.js:127)

     

在Subscriber.next(Subscriber.js:91)

     

在CatchSubscriber.Subscriber._next(Subscriber.js:127)

     

在CatchSubscriber.Subscriber.next(Subscriber.js:91)

     

在MapSubscriber._next(map.js:85)

ts:

    commitments: Array<Commitment>;
    selectedCommitment = null;
    reportingDates: Array<ReportingDate>;
    filteredReportingDates = [];
    id: number;
    routeId: any;
    public errorMsg;

    ngOnInit() {
        this.routeId = this.route.params.subscribe(
          params => {
            this.id = +params['id'];
          }
        )
        let commitmentRequest = this.route.params
          .flatMap((params: Params) =>
            this.servCommitment.getCommitment(+params['id' ]));
        commitmentRequest.subscribe(response => this.commitment = response.json(), error => this.errorMsg = error);

    }

  @Input() commitment: Commitment;

    onSelectedReportingDate(commitmentId) {
        this.selectedCommitment = this.commitments.find(
          (el) => {
            return el.commitment_id === commitmentId
          }
        );

        this.servReportingDate.getReportingDates().subscribe(
          reportingDate => {
            this.reportingDates = reportingDate;
            this.filteredReportingDates = this.reportingDates.filter(
              (reportingDate) => reportingDate.l_commitments_id === this.selectedCommitment.commitment_id
            );
          }
        );
    }

html:

<div *ngIf="commitment">
 <button type="submit" class="btn btn-info btn-simple" (click)="onSelectedReportingDate(commitment.commitment_id)">Test</button>
  <div *ngIf="selectedLiability">
   <div *ngFor="let reportingDate of filteredReportingDates">
        {{ reportingDate.reportingdate_plan }}
   </div>
  </div>
</div>

第87-88-89行:

  this.filteredReportingDates = this.reportingDates.filter(
    (reportingDate) => reportingDate.l_commitments_id === this.selectedCommitment.commitment_id
  );

2 个答案:

答案 0 :(得分:2)

您只需要对变量this.selectedCommitment进行null或未定义检查即可。

@Sachila Ranawaka代码的小修改:

(reportingDate) => this.selectedCommitment && (reportingDate.l_commitments_id === this.selectedCommitment.commitment_id)

答案 1 :(得分:1)

检查变量中是否存在commitment_id

(reportingDate) => this.selectedCommitment && (reportingDate.l_commitments_id === this.selectedCommitment.commitment_id)