我需要将Set<string>
属性转换为json,反之亦然,但是事实证明,它在Angular中不可用。
我想要实现的就是每当我具有json属性,例如:roles: ['role1', 'role2']
时,我需要将其转换为typescript属性,例如:roles: Set<string>;
。
问题:如何在不使用外部库的情况下将json数组转换为Angular中的Set和Vise,反之亦然?如果那不可能:如何以一种更优雅的方式实现这一目标,那么我现在拥有。
我现在如何做:
我通过以下方式组合使用HttpClient
和class-transformer lib通话:
export class User {
@Transform(value => new Set(value))
roles: Set<string>;
// some other properties
toJSON() {
let result: any = {};
for (let property in this) {
let field: any = this[property];
if (field instanceof Set) {
result[property] = Array.from(field);
} else {
result[property] = field;
}
}
return result;
}
}
然后在http通话中:
his.http.get<User>(url)
.map(res => plainToClass(User, res));
@Transform
和plainToClass
都来自class-transformer的地方。
效果很好,但是我想摆脱这段代码。