响应对象中的Angular 4 Typescript解析枚举接口属性 [英] Angular 4 typescript parsing enum interface attribute in response object
问题描述
我有一个来自API的响应,该响应返回一个枚举值.从API返回的值在请求中表示为字符串.
此值是打字稿界面的enum
属性.
I have a response from API which is returning a enum value. value returned from API is represented as a string in request.
This value is a enum
attribute of typescript interface.
问题:
收到响应时,TS接口将该值存储为字符串(可能就是问题所在),因此我不能将其直接用作enum
.
Problem:
when receiving a response, TS interface store that value as a string (probably thats the issue) so i can't use it directly as enum
.
obj模型:
export interface Condo {
id:number
title:string
latitude:number
longitude:number
city:string
country:string
district:string
address:string
locationType: LocationType
}
export enum LocationType {
CONDO,
MALL,
STATION
}
请求:
getCondoAllByCountry(country_code){
return this.http.get(this.config.apiEndpoint +this.subApiUrl+'/all')
.map(res => <Condo[]>res.json())
.catch((err:Response) => {
return Observable.throw(err.json());
});
}
使用示例:
this.condoService.getCondoAllByCountry(this.userData.country_code).subscribe(data=>{
someFunc(data)
})
............
someFunc(condo_list: Condo[]){
//here is need to know the `locationType` for each object
console.log(typeof condo_list[i].locationType);
console.log(typeof LocationType.CONDO)
switch (condo_list[i].locationType){
case LocationType.CONDO:
console.log('Case - condo')
break;
case LocationType.MALL:
console.log('Case - mall')
break;
case LocationType.STATION:
console.log('Case - station')
break;
}
}
因此,switch.. case
不适用于此属性.在console.log()
中,我得到了:
So, the switch.. case
is not working for this attribute. in console.log()
i'm getting:
console.log(typeof condo_list[i].locationType);
-string
console.log(typeof LocationType.CONDO)
-number
那么,这意味着存在一个解析概率,而condo_list[i].locationType
不是enum
(考虑它应该为枚举显示number
)?
So, that means that there were a parsing prob and condo_list[i].locationType
is not a enum
(considering it should show number
for enum)?
我应该如何解决?
推荐答案
如果使用的是打字稿2.4或更高版本,则可以声明字符串枚举,如下所示:
If you're using typescript 2.4 or above, you can declare string enums as follows:
export enum LocationType {
CONDO = 'CONDO',
MALL = 'MALL',
STATION = 'STATION'
}
// ...
switch (object.locationType) {
case LocationType.CONDO: // ...
case LocationType.MALL: // ...
case LocationType.STATION: // ...
}
在旧版本中,只能使用基于数字的枚举.在这种情况下,最好使用字符串文字联合类型:
In older versions, you're restricted to using number-based enums. In that case, you're probably better off using a string literal union type:
export type LocationType = 'CONDO' | 'MALL' | 'STATION';
// ...
switch (object.locationType) {
case 'CONDO': // ...
case 'MALL': // ...
case 'STATION': // ...
}
这篇关于响应对象中的Angular 4 Typescript解析枚举接口属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!