Javascript 错误类型错误:无法读取属性';推动';角6中的空值

Javascript 错误类型错误:无法读取属性';推动';角6中的空值,javascript,angular,Javascript,Angular,Cart是我的模型,它类似于 //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 { WebSt

Cart是我的模型,它类似于

//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;
}

是否先调用
getproducts
?如果是,记录的是什么?是的,我正在onInit()上调用getproducts,记录的是什么?如果在记录的
getproducts
中将其设置为null,则将其设置为空数组不会有任何帮助??在我没有获得uIn
getproducts
的地方,您有一行:
console.log(this.mycart)
,它应该将
this.mycart
的值记录到开发人员控制台。