0

contact-bar.component.ts

saveContacts(): void{
var contact = new Contact({});
contact.id = 1;
contact.name = 
(<HTMLInputElement>document.getElementById("contactName")).value;
contact.mobile = parseInt((<HTMLInputElement>document.getElementById("contactMobile")).value);
this.contactService.saveContact(contact);
}

contact.service.ts

saveContact(contact: Contact) {
    var contacts: Array<Contact> = 
JSON.parse(LocalStorage.getItem("contacts"));
    contacts.push(contact);
    localStorage.setItem("contacts", JSON.stringify(contacts));
}

Error: Cannot read property 'push' of null

Om Patel
  • 227
  • 1
  • 3
  • 9

1 Answers1

0

Firstly regarding your error: you are receiving Cannot read property 'push' of null because you are trying to get the contact data (through localstoarge) which is not there. That's why while pushing the data into the array you're prompted with that error.

However, There are some issues in your code which need to be fixed.

  1. Remove this line: var contacts: Array<Contact> = JSON.parse(LocalStorage.getItem("contacts"));

  2. Instead of sending data as an array try the following:

Code:

var contact =  {
    contact.id : 1;   
    contact.name:(<HTMLInputElement>document.getElementById("contactName")).value;  
    contact.mobile: parseInt((<HTMLInputElement>document.getElementById("contactMobile")).value);
    }

this.contactService.saveContact(contact);

**contact.service.ts**

saveContact(contact: any) {
    localStorage.setItem("contacts", JSON.stringify(contact));
}
iamdanchiv
  • 4,052
  • 4
  • 37
  • 42
Kamaal
  • 61
  • 5