问题
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.
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 model:
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
}
request:
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());
});
}
usage sample:
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;
}
}
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
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)?
How should i fix it?
回答1:
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': // ...
}
来源:https://stackoverflow.com/questions/45539033/angular-4-typescript-parsing-enum-interface-attribute-in-response-object