gpt4 book ai didi

angular - 了解 ngOnInit

转载 作者:搜寻专家 更新时间:2023-10-30 21:44:09 26 4
gpt4 key购买 nike

我正在学习有关 Angular udemy 类(class),并遇到了这段代码。我有一个示例项目,它有一个添加项目按钮,可以在数组中添加一个新项目并在屏幕上显示更新的数组。

shopping-edit.component.ts

export class ShoppingEditComponent implements OnInit {

@Input() ingredientsArray : Ingredient[];

shoppingItemName : string = 'Test';
shoppingItemAmount : number = 66;

constructor(private shoppingListService : ShoppingListService) { }

ngOnInit() {
}

onItemAdd(){
console.log(this.shoppingItemName)
this.shoppingListService.addIngredient(this.shoppingItemName, this.shoppingItemAmount);
}

}

我有一个事件发射器,它在单击“添加”按钮时发射更新后的数组。

购物 list .service.ts

ingredientsChanged = new EventEmitter<Ingredient[]>();

addIngredient(name: string, value : number){
this.ingredients.push(new Ingredient(name, value));
this.ingredientsChanged.emit(this.ingredients.slice());
}

为了显示列表,我正在使用 shopping-list.component.ts


export class ShoppingListComponent implements OnInit {

constructor(private shoppingListService : ShoppingListService){}

ingredients : Ingredient[];


ngOnInit() {
this.ingredients = this.shoppingListService.getIngredients();
this.shoppingListService.ingredientsChanged.subscribe(
(ingredients : Ingredient[]) => {
this.ingredients = ingredients;
}
)
console.log("hello")
}

}

由于 shopping-list.component.ts 的 ngOnInit() 只运行一次,每次单击“添加”按钮时如何显示更新的列表?

最佳答案

您的列表未在 ngOnOInit 中更新。您只是在 ngOnInit 中订阅了一个可观察对象。因此,每当您在订阅中收到新数据时,您就会更新一个变量,因为 ngOnChanges 会被触发,这将更新您的 View 。

关于angular - 了解 ngOnInit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58164704/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com