我想将我的枚举显示为字符串,但将其显示为数字。
我正在从Web服务接收json对象,并将其映射到我的Typescript对象
getProperties(): Observable<Property[]> {
return this.http.get<Property[]>(this.getallagentsproperties + '1');
}
export enum LetType {
Notspecified = 0,
LongTerm = 1,
ShortTerm = 2,
Commercial = 4
}
export class Property {
...other stuff...
letType: LetType;
...other stuff...
}
我的组件会进行调用并将其添加到相关属性中
import { Component, OnInit } from '@angular/core';
import { Property } from './Property';
import { PropertyService } from '../properties.service';
@Component({
selector: 'app-properties',
templateUrl: './properties.component.html',
})
export class PropertiesComponent implements OnInit {
properties: Property[];
constructor(private propertyService: PropertyService) { }
ngOnInit() {
this.getProperties()
}
getProperties(): void {
this.propertyService.getProperties()
.subscribe(p => this.properties = p);
}
}
当我在模板中显示
{{property.letType}}
时,将显示:4
我希望它显示商业广告我尝试遵循在添加的模板中找到here的答案
{{LetType[property.letType]}}
在我的Componant中,我添加了
LetType = this.LetType;
但我总是在控制台中收到以下错误
我究竟做错了什么?
最佳答案
您无需在此处创建管道。这是我的答案。
let-type.enum.ts
export enum LetType{
Type1 = 1,
Type2 = 2,
Type3 = 3,
Type4 = 4
}
property.model.ts
export interface Property{
...other stuff...
letType: LetType;
...other stuff...
}
properties.component.ts
import { Component, OnInit } from '@angular/core';
import { Property} from './property.model';
import { LetType} from './let-type.enum';
import { PropertyService } from '../properties.service';
@Component({
selector: 'app-properties',
templateUrl: './properties.component.html',
})
export class PropertiesComponent implements OnInit {
properties: Property[] = [];
LetType = LetType;
constructor(private propertyService: PropertyService) { }
ngOnInit() {
this.getProperties();
}
getProperties() {
this.propertyService.getProperties().subscribe(result => {
this.properties = result
});
}
}
然后在你的HTML
<ng-container matColumnDef="columnName">
<th mat-header-cell *matHeaderCellDef >Types</th>
<td mat-cell *matCellDef="let element">{{LetType[element.letType]}}</td>
</ng-container>