Angular 类型脚本类型化数组不显示数据
我使用Angular 7和Typescript 3在服务中创建一个预填充的成分数组,该数组将在组件中使用,但当我将该数组打印到控制台时,我得到的是一个空对象数组 如果我使用对象文本创建类型化数组,它将工作,但是如果我使用新操作符创建数组,数组将不包含任何数据 已编辑:添加了配料类的片段Angular 类型脚本类型化数组不显示数据,angular,typescript,typed-arrays,Angular,Typescript,Typed Arrays,我使用Angular 7和Typescript 3在服务中创建一个预填充的成分数组,该数组将在组件中使用,但当我将该数组打印到控制台时,我得到的是一个空对象数组 如果我使用对象文本创建类型化数组,它将工作,但是如果我使用新操作符创建数组,数组将不包含任何数据 已编辑:添加了配料类的片段 export class Ingredient { constructor(name?: string, amount?: number, measurement?: string) {} } 其中包含
export class Ingredient {
constructor(name?: string, amount?: number, measurement?: string) {}
}
其中包含以下数据:
export class ShoppingListService {
private ingredients: Ingredient[] = [{
name: 'shrimp',
amount: 1,
measurement: 'cup'
},
{
name: 'bib lettuce',
amount: 1,
measurement: 'bunch'
}];
constructor() {
console.log('ingredients', this.ingredients);
}
控制台输出:
ingredients [{name: "shrimp", amount: 1, measurement: "cup"},
{name: "bib lettuce", amount: 1, measurement: "bunch"}
]
ingredients [Ingredient{}, Ingredient{}]
这不包含数据
export class ShoppingListService {
private ingredients = [
new Ingredient('shrimp', 1, 'cup'),
new Ingredient('bib lettuce', 1, 'bunch')
];
constructor() {
console.log('ingredients', this.ingredients);
}
}
控制台输出:
ingredients [{name: "shrimp", amount: 1, measurement: "cup"},
{name: "bib lettuce", amount: 1, measurement: "bunch"}
]
ingredients [Ingredient{}, Ingredient{}]
我还尝试使用以下语法,但得到的输出与上面的示例相同:
private ingredients: Ingredient[] = [
new Ingredient('shrimp', 1, 'cup'),
new Ingredient('bib lettuce', 1, 'bunch')
];
这里有我遗漏的打字稿或角度逻辑吗?上述示例用于此处的角度文档:
因此,我认为您需要在您的配料类别中进行这些更改
export class Ingredient {
constructor(data?: any) {
this.name = data.name;
this.amount = data.amount;
this.measurement = data.measurement;
}
public name: string = null;
public amount: number = null;
public measurement: string = null;
}
并在组件内部设置数据
private ingredients = [
new Ingredient({
name: 'bib lettuce',
amount: 1,
measurement: 'bunch'
})
];
我希望它能帮助您您一定忘了正确设置配料类的构造函数。这就是我可以假设的问题。顺便问一下,第一逻辑有什么问题?你不能理解吗?配料类是什么样子的?我认为配料类有一些问题。如果你编写配料类,我们就可以确定你想要什么wrong@Yash这是我的配料课。我决定使用Typescript参数属性。我应该使用自动构造函数吗?我之所以没有这样做,是因为我认为它没有给我提供getter和setter。如果你想让构造函数参数成为属性,你需要给它们一个可见性,否则它们就是简单的参数。难道我不能使用参数属性来做这件事吗?您好@Esakki,您的答案与实际解决方案最接近。但是,由于我试图找到为什么
[新成分(…),新成分(…)]
不起作用的答案,如果您通过取消第二组代码的注释并删除对象文本来修改您的答案,我将接受您的答案。
**Working code for both scenario**
//ingredient.ts
export class Ingredient{
constructor(public name: string, public id: number, public measurment: string){
}
}
//ingredient.component.ts
import {Component} from '@angular/core';
import { Ingredient } from './ingredient ';
@Component({
selector: 'app-ingredient',
template: 'Ingredient'
})
export class IngredientComponent{
private ingredients: Ingredient[] = [{
name: 'shrimp',
id: 1,
measurment: 'cup'
},
{
name: 'bib lettuce',
id: 1,
measurment: 'bunch'
}];
/*
ingredients = [
new Ingredient('shrimp', 1, 'cup'),
new Ingredient('bib lettuce', 1, 'bunch')
];
*/
constructor(){
console.log(this.ingredients);
}
}