首页 > 解决方案 > Angular无法使用@Input读取未定义的属性

问题描述

我创建了一个在我的父组件中使用的组件:

<app-event-menu-nav [event]="event"></app-event-menu-nav>

这是组件:

import {Component, OnInit, ChangeDetectionStrategy, Input} from '@angular/core';
import {ScrollNavigationService} from "../../../shared/services/scroll-navigation/scroll-navigation.service";
import {AuthService} from "../../../shared/services/auth/auth.service";
import {EventModel} from "@event/core";

@Component({
  selector: 'app-event-menu-nav',
  templateUrl: './event-menu-nav.component.html',
  styleUrls: ['./event-menu-nav.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class EventMenuNavComponent implements OnInit {
  @Input() event: EventModel;

  constructor(
    private scrollService: ScrollNavigationService,
    public authService: AuthService
  ) {}

  ngOnInit(): void {}

  scrollTo(anchor: string, offset?: number) {
    this.scrollService.scrollToAnchor(anchor, { offset });
  }

  isOwner() {
    return this.authService.currentUserId === this.event.creator;
  }
}

和html

<nav class="secondary_nav">
  <div class="container">
    <ul>
      <li>
        <a (click)="scrollTo('description', -80 )">
          <i class="fal fa-file-alt"></i> {{ 'event.menu.description' | translate }}
        </a>
      </li>
      <li *ngIf="!event.onlineEvent">
        <a (click)="scrollTo('location', -60)"></a>
          <i class="fal fa-map-marker-alt"></i> {{ 'event.menu.location' | translate }}
      </li>
      <li>
        <a (click)="scrollTo('comments')">
          <i class="fal fa-comment"></i> {{ 'event.menu.comments' | translate }}
        </a>
      </li>
      <li *ngIf="isOwner()" >
        <a [routerLink]="['/organization/event', event?.id]">
          <i class="fal fa-cog"></i> {{ 'event.menu.admin' | translate }}
        </a>
      </li>
    </ul>
  </div>
</nav>

我在尝试运行 Karma 测试时遇到问题:

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

我不知道为什么我会遇到这个问题。我必须在我的 上添加一些东西spec.ts吗?

标签: angulartypescript

解决方案


如果eventundefined,则此处的评估event.onlineEvent失败:

<li *ngIf="!event.onlineEvent">

您可以在定义之前阻止模板呈现event,例如通过*ngIful:

<ul *ngIf="event">
  [...]
  <li *ngIf="!event.onlineEvent">

如果值总是被定义并且只在单元测试中失败,这意味着你应该在单元测试的上下文中给出一个值。例如,像这样:

component = fixture.componentInstance;
component.event = [...]
fixture.detectChanges();

推荐阅读