angular - 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
吗?
解决方案
如果event
是undefined
,则此处的评估event.onlineEvent
失败:
<li *ngIf="!event.onlineEvent">
您可以在定义之前阻止模板呈现event
,例如通过*ngIf
在ul
:
<ul *ngIf="event">
[...]
<li *ngIf="!event.onlineEvent">
如果值总是被定义并且只在单元测试中失败,这意味着你应该在单元测试的上下文中给出一个值。例如,像这样:
component = fixture.componentInstance;
component.event = [...]
fixture.detectChanges();
推荐阅读
- python - Python selenium 谷歌地图元素无法定位
- c# - 检查 gRpc 服务器是否正在为 Grpc.Net.Client 运行
- asp.net-core - 在云中创建 Blob 存储 UNC 路径
- typescript - 如何在合并对象中为 createEntityAdapter 对象的 getInitialState 键入属性?
- windows - 使用 NetNamedPipeBinding 使 Windows 10 上的每个人都可以访问 WCF 主机
- elasticsearch - 使用 elasticsearch 7.x 客户端 PUT 显式映射
- mongoose - 我可以从子架构访问基本架构方法吗?
- firebase - 半秒后,snapshot.data 变为空
- python - 如何在函数中一次使用列表/元组一个元素?
- windows - 如何制作 Clippy(Windows 虚拟助手)克隆?