这里,使用JSON字符串初始化变量some
我需要扩展,因此缩进以提高可读性。
export class MyComponent implements OnInit {
some:any = JSON.parse('[{"id":"EN","fill":"blue","classb":"FR someclass"},{"id":"US","fill":"hsl(240, 100%, 35%)","classb":"someclass"},{"id":"ES","fill":"hsl(240, 100%, 60%)","classb":"someclass"},{"id":"IT","fill":"hsl(240, 100%, 90%)","classb":"someclass"}]');
getStyle(zoneId:string):String{
var test = this.some.find(x => x.id === zoneId);
if( test === undefined) return "#000000";
if( test.fill != undefined) return test.fill;
return "red";
}
}
如何使用缩进的JSON来初始化TypeScript / Angular类成员?
答案 0 :(得分:2)
您可以使用反引号创建template string,这样可以为格式化的JSON字符串添加换行符:
class MyComponent {
some = JSON.parse(`
[
{
"id": "EN",
"fill": "blue",
"classb": "FR someclass"
},
{
"id": "US",
"fill": "hsl(240, 100%, 35%)",
"classb": "someclass"
},
{
"id": "ES",
"fill": "hsl(240, 100%, 60%)",
"classb": "someclass"
},
{
"id": "IT",
"fill": "hsl(240, 100%, 90%)",
"classb": "someclass"
}
]
`);
}
答案 1 :(得分:1)
只需使用一个对象。 JSON实际上是JavaScript的一部分(出于所有意图和目的)。
您根本不需要嵌入字符串。
例如,您可以编写以下内容
export class MyComponent implements OnInit {
some = [ // note removed `: any` as it degrades tooling esp when there is an initializer
{"id": "EN", "fill": "blue", "classb": "FR someclass"},
{"id": "US", "fill": "hsl(240, 100%, 35%)", "classb": "someclass"},
{"id": "ES", "fill": "hsl(240, 100%, 60%)", "classb": "someclass"},
{"id": "IT", "fill": "hsl(240, 100%, 90%)", "classb": "someclass"}
];
getStyle(zoneId: string): string { // note correct type is `string` not `String`
var test = this.some.find(x => x.id === zoneId);
if (test === undefined) return "#000000";
if (test.fill != undefined) return test.fill;
return "red";
}
}
这样可以提供完整的工具和语言级别支持,同时允许使用JavaScript允许的所有可能性进行表达格式化。