2016-03-15 38 views
1

我正在學習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()我從服務中獲得的另一種成分,並將它推到陣列。

問題是,每次切換組件並返回到倉庫組件時,組件列表都會重置,就像即使組件列表不在構造函數中一樣,也不會修改該數組。

我做錯了什麼?該文件不是很清楚這一點,我會感謝一些幫助。

感謝

+0

您可以將組件類列表保留在組件類之外,每當您導航到它時都會重新創建組件,這樣您將會改變全局數組而不是類屬性。參見例如[plnkr](http://plnkr.co/edit/236GOzUbemgGNwnKO7fD?p=info)。 –

回答

4

有幾種方法可以做到這一點:

  • Eric提供的解決方案。
  • 使用共享服務。特別是如果你想分享這些數據對幾個組件。在這種情況下,必須在引導應用程序時定義服務,並且不要在組件的providers屬性中再次指定服務。
  • 如果您的組件涉及到路由,您可以使用CanReuse接口告訴Angular2重新使用組件的同一個實例。請參閱此文檔:https://angular.io/docs/ts/latest/api/router/CanReuse-interface.html
+0

謝謝你,所有的答案都是有效的,但我接受你的答案,因爲你給了更多的選擇。在服務中包含數組運行良好。 –

3

您需要的ingredients陣列添加IngredientService內,並添加服務爲引導方法:

bootstrap(AppComponent, [ 
    ..., 
    IngredientService]); 

IngredientService將是一個單身,你的成分數組不會先復位