2017-08-29 24 views
-1

关于addItem项目被push到productList数组中,但是在点击cart选项卡后,cartcomponent中的productList会被重新初始化(清空productList数组)。如何避免重新初始化数组?点击组件,成员变量是否得到重新初始化?任何其他方法来避免它?

export class CartComponent implements OnInit { 
    public productList: any[] = []; 
    constructor(private ShopDataService: ShopDataService) { 
     this.ShopDataService.getValue() 
      .subscribe(
       products => { 
        this.productList.push(products); 
        console.log("cart::" + this.productList); 

       }); 

    } 
} 


export class ShopDataService { 
    private products: BehaviorSubject <any[]> = new BehaviorSubject([]); 
    constructor() {} 
    public setValue(value): void { 
     this.products.next(value); 
    } 

    public getValue(): Observable <any[]> { 
     return this.products; 
    } 

} 
+0

你可以分享更多的代码? –

+1

点击相同的活动标签时出现问题? –

+1

我正在将产品从另一个组件添加到购物车,并查看购物车(添加到购物车的产品列表)我必须点击购物车标签 – sue

回答

0
export class CartComponent implements OnInit { 
public productList: any[] = []; 
constructor(private ShopDataService: ShopDataService) { 
    this.productList = this.ShopDataService.oldList; 
    this.ShopDataService.getValue() 
     .subscribe(
      products => { 
       this.productList.push(products); 
       this.ShopDataService.oldList = this.productList; 
       console.log("cart::" + this.productList); 

      }); 

}} 
export class ShopDataService { 
    public oldList : any[]; 
    private products: BehaviorSubject <any[]> = new BehaviorSubject([]); 
    constructor() {} 
    public setValue(value): void { 
      this.products.next(value); 
    } 

    public getValue(): Observable <any[]> { 
      return this.products; 
    } 

}

试试这个

+1

在这一行,this.ShopDataService.oldList = this.productList;在组件中,它再次重置数组 – sue

+1

您是否在根cofig或模块页面中注入了ShopDataService ..? –

+1

它应该只在整个应用程序中配置一次 –

相关问题