我正在學習AngularJS2並在他們的網站中關注My Hero教程我正在構建一個應用程序,並且我正在嘗試瞭解如何將項目存儲在內存中。Angular 2如何在內存中存儲項目
這是我的組件:
@Component({
selector: 'my-warehouse',
templateUrl: 'templates/warehouse.component.html',
styleUrls: ['css/warehouse.component.min.css']
})
export class WarehouseComponent {
ingredients: Ingredient[] = [
{"id": 100, "name": "Milk", "description": "White and delicious.", "quality": 0, "price": 10, "quantity": 20},
{"id": 101, "name": "Cocoa", "description": "Ready to be processed into sweet chocolate.", "quality": 0, "price": 20, "quantity": 50},
{"id": 102, "name": "Sugar", "description": "The magic behind the choco.", "quality": 0, "price": 5, "quantity": 10}
];
constructor(
private _router: Router,
private _ingredientService: IngredientService){
}
addIngredient(){
var ingr = jQuery.extend({}, this._ingredientService.getIngredient(104));
ingr.quantity = 15;
ingr.quality = 0;
this.ingredients.push(ingr);
}
}
我有一個數組稱爲ingredients
有一些成分已經構成,當我使用addIngredient()我從服務中獲得的另一種成分,並將它推到陣列。
問題是,每次切換組件並返回到倉庫組件時,組件列表都會重置,就像即使組件列表不在構造函數中一樣,也不會修改該數組。
我做錯了什麼?該文件不是很清楚這一點,我會感謝一些幫助。
感謝
您可以將組件類列表保留在組件類之外,每當您導航到它時都會重新創建組件,這樣您將會改變全局數組而不是類屬性。參見例如[plnkr](http://plnkr.co/edit/236GOzUbemgGNwnKO7fD?p=info)。 –