我有一个InMemoryDataService
用于Angular应用程序。
最初的代码看起来像这样:
createDb() {
const borders = [
{ id: 1, name: 'Front border' },
{ id: 2, name: 'Potager' },
];
return { borders };
}
哪个有效。
我把它改为:
public readonly borders: Border[];
constructor() {
this.borders = [
{ id: 1, name: 'Front border' },
{ id: 2, name: 'Potager' },
];
}
createDb() {
return { this.borders };
}
出现以下错误:
':' expected
在createDb方法中。我不明白这个错误的原因。
如果我将代码更改为:
createDb() {
const bordersCopy = this.borders;
return { bordersCopy };
}
一切都很好。但我不明白为什么。
为什么我不能归还该属性,但我可以返回已分配属性的局部变量?
答案 0 :(得分:2)
以下格式是ES2015的功能,称为Property value shorthand
,如果您在variable
对象括号内提及{ }
名称,它将隐式创建一个与赋值变量具有相同名称的属性
return { borders };
//similar to
//return { borders: borders };
由于以下其他语法不起作用,因此,您直接在Object
中提取了一些从中提取的值。
createDb() {
return { this.borders };
//interpreted as
// return { 'borderValue' }; //which is syntactically and semantically wrong.
}
您可以按照下面的说法解决问题。
createDb() {
return { borders: this.borders };
}