我試圖在將項目添加到購物籃時更新購物車計數,但我認爲唯一的方法是使用localStorage
保存項目但是我想更新一旦用戶添加一個項目,用戶界面。Angular 2使用SharedService將項目推送到陣列以更新UI
所以我認爲我可以創建一個SharedService
並將其推送到那裏,但是如何在用戶添加項目時從該服務檢索項目的array
以更新UI?
SharedService迄今爲止 -
export class SharedServiceService {
public itemArr: any = [];
constructor() { }
itemCollection(item) {
this.itemArr.push(item);
console.log(this.itemArr);
}
}
我AddToBasket組件功能 -
addToBasket(itemCode) {
this.sharedServiceService.itemCollection(itemCode);
}
我想從我的app.component
檢索項目的array
,認爲這會是這麼簡單但是它不是這個this.basketCount
返回[]
空數組。我想展示的是array
長度(10) Items
。
ngOnInit() {
// console.log(this.sharedServiceService.itemArr);
this.basketCount = this.sharedServiceService.itemArr;
}
哦,你是天才的先生!以爲我必須訂閱它或什麼。 – MrNew
很高興它的工作,如果你要使用計數很多,你可能想要創建一個計算屬性:'私人get basketCount():數字{返回this.sharedService.itemArr.length; }'然後直接插入'{{basketCount}}'。陣列也一樣。 – kontiki
介意更新您的答案,以便閱讀? – MrNew