Angular 2如何在内存中存储项目

Ait*_*lez 1 typescript angular

我正在学习AngularJS2,并在他们的网站上遵循“我的英雄”教程,正在构建一个应用程序,并试图了解如何在内存中存储项目。

这是我的组件:

@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);
    }

}
Run Code Online (Sandbox Code Playgroud)

我有一个ingredients已调用的数组,其中已经构造了一些成分,当我使用addIngredient()时,我从服务中获取了另一个成分并将其推入数组。

问题是,每次我切换组件并返回到仓库组件时,都会重置成分列表,就像即使该成分列表不在构造函数之外也从未修改过数组一样。

难道我做错了什么?该文档对此不是很清楚,我将不胜感激。

谢谢

Thi*_*ier 5

有几种方法可以做到这一点:

  • Eric提供的解决方案。
  • 使用共享服务。特别是如果您要针对多个组件共享这些数据。在这种情况下,必须在引导应用程序时定义服务,并且不会在providers组件的属性中再次指定该服务。
  • 如果您的组件涉及布线,则可以使用该CanReuse接口告诉Angular2重用该组件的相同实例。参见此文档:https : //angular.io/docs/ts/latest/api/router/CanReuse-interface.html