Bob*_*bby 4 typescript angular
我正在使用这个库
tl; dr:如何忽略打字稿中的“未定义属性”
为了创建自定义 plonter,文档说要查看他们的实现,我复制了他们的基本代码,模板如下所示 =>
<ac-html *ngIf="plonterService.plonterShown" [props]="{
position: plonterPosition
}">
<div class="plonter-context-menu">
<div *ngFor="let entity of plonterService.entitesToPlonter">
<div class="plonter-item" (click)="chooseEntity(entity)">
{{ entity?.name || entity?.id }}
</div>
</div>
</div>
</ac-html>
Run Code Online (Sandbox Code Playgroud)
组件
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { CoordinateConverter, PlonterService } from 'angular-cesium';
@Component({
selector: 'app-entity-plonter',
templateUrl: './entity-plonter.component.html',
styleUrls: ['./entity-plonter.component.less'],
providers: [CoordinateConverter],
})
export class EntityPlonterComponent implements OnInit {
constructor(public plonterService: PlonterService,
private chandeDetector: ChangeDetectorRef,
private coordinateConverter: CoordinateConverter) { }
ngOnInit() {
this.plonterService.plonterChangeNotifier.subscribe(() => this.chandeDetector.detectChanges());
}
get plonterPosition() {
if (this.plonterService.plonterShown) {
const screenPos = this.plonterService.plonterClickPosition.endPosition;
return this.coordinateConverter.screenToCartesian3(screenPos);
}
}
chooseEntity(entity: any) {
this.plonterService.resolvePlonter(entity);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我在模板中有错误就行了
{{ entity?.name || entity?.id }}
Run Code Online (Sandbox Code Playgroud)
AcEntity 没有属性名称和 ID。
这是因为在lib中,AcEntity是这样定义的
/**
* Angular Cesium parent entity, all entities should inherit from it.
* ```typescript
* entity= new AcEntity({
* id: 0,
* name: 'click me',
* position: Cesium.Cartesian3.fromRadians(0.5, 0.5),
* });
* ```
*/
export class AcEntity {
/**
* Creates entity from a json
* @param json entity object
* @returns entity as AcEntity
*/
static create(json?: any) {
if (json) {
return Object.assign(new AcEntity(), json);
}
return new AcEntity();
}
/**
* Creates entity from a json
* @param json (Optional) entity object
*/
constructor(json?: any) {
Object.assign(this, json);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我知道错误是合法的,但我想在编译和构建中忽略它。由于我无法直接控制图书馆,而且价值来自图书馆的服务。
是否可以 ?
小智 7
我不知道是否有人仍在为此寻找答案,但只是想我会添加我为它找到的答案。您可以通过用 $any(object) 包装对象来避免模板错误。所以,在这种情况下,它看起来像:
<div *ngFor="let entity of $any(plonterService).entitesToPlonter">
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1925 次 |
| 最近记录: |