I'm attempting to transfer information from a "blog" to "blogs", but encountering a hiccup in the process

I encountered the following issue:

**Error1:** Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables, such as Arrays. Did you mean to use the keyvalue pipe? 
**Error2:** this.blogs.push is not a function

This is an excerpt from my code:

export class BlogComponent {
  blogs: Array<blogType>;

  constructor() {
    this.blogs = new Array<blogType>();
  }

  ngOnInit() {
    this.blogs = JSON.parse(localStorage.getItem("blogs")!);
  }

 addBlog(title: any, content: any) {

    let blog = new blogType(title.value, content.value);
    if (localStorage.getItem('blogs')) {
      this.blogs = JSON.parse(localStorage.getItem('blogs')!);
    }

    this.blogs.push(blog); //error occurs because of that line. Runtime error
    localStorage.setItem('blogs', JSON.stringify(this.blogs));
    title.value = '';
    content.value = '';
    alert('Blog Added!');
  }

I am attempting to transfer data from the "blog" array and insert it into the "blogs" array for storage in localstorage. However, there is an error arising due to the line: this.blogs.push(blog);

Answer №1

Make sure to verify if LocalStorage is empty before parsing its contents and assigning it to this.blogs:

ngOnInit() {
    var storedData = localStorage.getItem('blogs');
    if (storedData !== null) {
      this.blogs = JSON.parse(storedData);
    }
    console.log('this.blogs contains: ' + this.blogs);
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Filling out form controls with a variety of values

I'm currently working on a form that features multiple select dropdowns generated from data retrieved from an API. Although unsure if I'm approaching this correctly, I've managed to populate the form for the 'appointmentPackages' ...

Dealing with multiple queryParams in Angular2: Best practices

Need help implementing a filtering mechanism in my new Angular2 app. Looking to filter a list of entries in an array based on around 20 properties. I've set up filters in one component and a list component as a child that is routed to. Initially, pas ...

Deploying an Angular application in a NodeJS environment using Azure DevOps

Can Azure DevOps Pipelines be used to automate the deployment of an Angular application to NodeJS or an on-premise WebServer? ...

Remove an item from the DOM instantly with React

Having trouble synchronously removing a child from the container? Here is a simplified code snippet demonstrating the current solution using the useState hook. type ChildProps = { index: number; id: string; remove: (index: number) => void; }; fun ...

Filling a data entry with simultaneous commitments

Sample code: type Alphabet = 'a' | 'b' | 'c'; const alphabetMap: Record<Alphabet, null> = { 'a': null, 'b': null, 'c': null} // Select any asynchronous processing function you prefer funct ...

What is the best way to delay an observable from triggering the next event?

In my Angular project, I am implementing RxJs with two subjects. s1.next() s1.subscribe(() => { // perform some operation and then trigger the event for s2 s2.next() }); s2.subscribe(() => { // perform some operat ...

Obtain a hidden item using *ngIf in Angular for testing purposes

Snippet of HTML Code: <div *ngIf="state"> <p>some text<p> <button (click)="increment()" class="myButton">Increment</button> </div> My Component Structure: @Component( ...

What is the best way to transfer variables from an ng-template defined in the parent component to a child component or directive?

Is there a way to pass an ng-template and generate all its content to include variables used in interpolation? As I am still new to Angular, besides removing the HTML element, do I need to worry about removing anything else? At the end of this ...

Derive data type details from a string using template literals

Can a specific type be constructed directly from the provided string? I am interested in creating a type similar to the example below: type MyConfig<T> = { elements: T[]; onUpdate: (modified: GeneratedType<T>) => void; } const configur ...

Parsing CSV files and converting string values to numerical doubles

I'm completely new to Java and currently working on reading a CSV file using openCSV. The code I have written is as follows: import java.io.FileReader; import java.util.Arrays; import au.com.bytecode.opencsv.CSVReader; public class ParseCSVLineByLi ...

Explaining the process of defining an object type in TypeScript and the conversion from JavaScript

Currently, I am attempting to enhance the background of a React website developed in typescript (.tsx) by incorporating particles. My approach involves utilizing the particle-bg component available at: https://github.com/lindelof/particles-bg However, whe ...

Utilizing the Google Geocode API to handle a promise with a substantial array

My Objective To efficiently process a large array using the .map method and interact with the Google Geocoder API through promises to get location data. The goal is to utilize Promise.all to store results in a .json file upon completion of the operation. ...

There seems to be an issue where the program is unable to properly output the complete array of strings in C. It's either displaying nothing at all or just the first character

I am trying to print all the elements in this code using an array, but it is not working as expected. #include <stdio.h> #include <stdlib.h> //#include "student_info.h" int main() { char animals[3]; animals[0] = "lion&q ...

JavaScript - Cannot access the 'name' property on an empty object

I am currently following a React tutorial that demonstrates how to create a useForm hook for linking form input to state. Here is the implementation of the hook: const useForm = (initial = {}) => { const [inputs, setInputs] = useState(initial) ...

Ways to retrieve an array following a function call

After a lot of testing and troubleshooting, I finally got my array to function properly in the console. However, when I click the button, the array is displayed on the console but not in my HTML. TS: jogar(){ for(var u=0;u<6;u++){ this.y ...

What is the reason behind the never return value in this typescript template?

As demonstrated in this example using TypeScript: Access TypeScript Playground type FirstOrSecond<condition, T1, T2> = condition extends never ? T1 : T2 type foo = never extends never ? () => 'hi' : (arg1: never) => 'hi' ...

What is the best way to ensure that the operations are not completed until they finish their work using RX

Is there a way to make RXJS wait until it finishes its work? Here is the function I am using: getLastOrderBeta() { return this.db.list(`Ring/${localStorage.getItem('localstorage')}`, { query: { equalTo: fa ...

Various modules in the project need to have distinct GitHub origins, particularly in the case of Spring-Angular

My goal is to create a well-structured project with separate frontend and backend modules. Here is the initial project structure: https://i.stack.imgur.com/EghPA.png I have attempted this in various configurations before, but every time I try, git recogn ...

Angular 4: Prevent the HTML template of the parent component from being rendered in the

My component has the following routes: { path: ':id', component: ProjectDetailsComponent, children: [ {path: '', redirectTo: 'gathering', pathMatch: 'full'}, {path: ' ...

When using AngularJS 2, the class identity is lost when resolving a Promise during fetching

SUMMARY: I'm encountering an issue where I am fetching Object instances instead of Org instances from my data in Angular 2. Is there a way to retrieve Org objects directly or is this the expected behavior? DETAILS: In my Angular 2 project, I have mod ...