[英]ERROR TypeError: Cannot read property 'push' of null in Angular 6
購物車是我的模特,它像
//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;
}
}
我已經看過答案了,但是沒有找到相關的答案,我對Angular還是很陌生,所以對此沒有太多的想法,將不勝感激
根據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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.