购物车是我的模特,它类似于
//declaring a cart model for products to add
export class Cart{
id:string;
name:string;
quantity:number;
picture:string;
}
这是我的服务app.service.ts
import { Injectable, Inject } from "@angular/core";
import { WebStorageService, LOCAL_STORAGE } from "angular-webstorage-service";
import { Cart } from "./models/cart.model";
@Injectable({providedIn:'root'})
export class AppService{
key="Product";
mycart:Cart[]=[];//creating a cart array
constructor(@Inject(LOCAL_STORAGE) private storage: WebStorageService) {
}
addtocart(id:string,name:string,quantity:number,picture:string){
var newcart:Cart={id:id,name:name,quantity:quantity,picture:picture};
this.mycart.push(newcart);//this gives me error
this.storage.set(this.key, this.mycart);//saving cart to the local storage
}
getproducts(){
this.mycart= this.storage.get(this.key);
console.log(this.mycart);
return this.mycart;
}
}
我已经看过答案了,但是没有找到相关的答案,我对棱角还很陌生,所以对它一点都不了解,将不胜感激
答案 0 :(得分:0)
根据您的console.log,您将其设置为null,因此为什么显示null
您应该检查this.storage.get(this.key);
是否返回null,并且仅将this.mycart
设置为非null。试试这个:
getproducts(){
cont storedCart = this.storage.get(this.key);
if (storedCart != null) {
this.mycart = storedCart;
}
return this.mycart;
}