Save information on the server and organize it into an array for use in local operations

Currently, I am working on the ShoppingApp using Angular for the front-end and Firebase for the backend. I have defined a model for the category as follows:

import { ProductModel } from "./product.model";

export class CategoryModel {

public id: number;
public name: string;
public description: string;
public image: string;
public products?: ProductModel[];


constructor(id: number, name: string, description: string, image: string, products: ProductModel[]) {
    this.id = id;
    this.name = name;
    this.description = description;
    this.image = image;
    this.products = products;
}
}

I have set up a service called data-storage-service.ts to handle fetching and storing data from Firebase.

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'Authorization': 'my-auth-token'
  })
}

@Injectable()
export class DataStorageServiceService {


  private heroesUrl = 'https://ng-recipefirebaseio.com/application.json';
  // URL to web api

  constructor(private http: HttpClient) { }


  storeCategoryList(productList: CategoryModel): Observable<CategoryModel> {
    return this.http.post<CategoryModel>(this.heroesUrl, productList).pipe(
      catchError(this.handleError<CategoryModel>('addCategory'))

    )


  }
  getHeroes(): Observable<CategoryModel[]> {
    return this.http.get<CategoryModel[]>(this.heroesUrl)
      .pipe(
        catchError(this.handleError('getHeroes', []))
      );
  }


  private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      console.error(error); // log to console instead

         return of(result as T);
    };
  }
}

My admin component is all set up, and I have integrated Modals from ngx-bootstrap. The purpose of these Modals is to send data to the server using Reactive Forms for validation. Below is a snippet of the admin component:

@Component({
  selector: 'app-admin',
  templateUrl: './admin.component.html',
  styleUrls: ['./admin.component.css']
})
export class AdminComponent implements OnInit {

  category = <CategoryModel>{};


  //  category: CategoryModel[] = [];
  categoryList: CategoryModel[] = []
  categoryForm: FormGroup;
  modalRef: BsModalRef;


  constructor(private productsService: ProductsService, private dataStorageServiceService: DataStorageServiceService, private modalService: BsModalService) { }

  ngOnInit() {
    this.getCategory();
    this.initForm();

  }


  getCategory(): void {
    this.dataStorageServiceService.getCategory()
      .subscribe(category => this.categoryList = category);
  }



  storeCategoryList() {
    const nameCategory = this.categoryForm.value.name;
    const descriptionCategory = this.categoryForm.value.category;
    this.category.name = nameCategory;
    this.category.description = descriptionCategory;
    this.category.id = 1;
    this.category.products = null;
    this.dataStorageServiceService.storeCategoryList(this.category).subscribe(

      (category: CategoryModel) => {
        this.categoryList.push(category)
      }

    )
  }

  openModal(template: TemplateRef<any>) {
    this.modalRef = this.modalService.show(template);
  }

  private initForm() {
    this.categoryForm = new FormGroup({
      'name': new FormControl(null, Validators.required),
      'description': new FormControl(null, Validators.required)
    })
  }


}

An issue arises when trying to store data in the list categoryList, with the error message

ERROR TypeError: _this.categoryList.push is not a function
. Additionally, the data being stored in Firebase appears as shown in the following image:

https://i.sstatic.net/1WHvF.png

Upon calling the method getCategory(), the output is displayed as follows:

https://i.sstatic.net/N54MQ.png

Answer №1

Based on the function name "getCategory," it appears that the function is designed to retrieve a single category. Due to this, your categoryList is not treated as an array during runtime, causing it to lack a push method and resulting in the error you're experiencing.

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

Create a series of buttons in Angular 2 that are linked to components with a click event

I am facing an issue with a component that generates a list of buttons, where I want to connect the click event to show a child component. The problem is that my current implementation using a local variable causes all buttons to display the last child com ...

The 'resp' parameter is assumed to have an unspecified type, shown as 'any'. This is an error in Angular

} ErrorHandler(response){ console.debug(response.json()); } DataHandler(response){ this.ClientModels = response.json(); } I have developed two functions to handle error and success responses, but an error message is showing up saying "para ...

Error message: Unable to assign value to 'kind' property as it is undefined in Angular Webpack application

Unexpectedly, my Angular application is encountering an error during the build process. TypeError: C:\Users\c\dev\privacy\node_modules\@fortawesome\angular-fontawesome\fesm2020\angular-fontawesome.mjs: Cannot se ...

Expanding Mongoose Schema with Typescript: A Comprehensive Guide

Currently, I am in the process of creating 3 schemas (article, comment, user) and models that share some common fields. For your information, my current setup involves using mongoose and typescript. Mongoose v6.1.4 Node.js v16.13.1 TypeScript v4.4.3 Eac ...

I have successfully set up micro-cors on my system, and as I tried to compile, I received the following outcome

While working on the Next.js Stripe project, I ran into an unexpected problem that I need help with. ./src/pages/api/webhooks.ts:3:18 Type error: Could not find a declaration file for module 'micro-cors'. 'E:/Project/longlifecoin/node_module ...

Encountering an issue with Ionic forms: Error message NodeInjector: NOT_FOUND [ControlContainer] is displayed

I have developed an Ionic application with a form. Everything was working fine until I integrated the form group and related elements into my code. Since then, I've been encountering this error: core.js:6260 ERROR Error: Uncaught (in promise): Erro ...

Synchronizing Form Data in Angular 5: Pass and Populate Dropdowns between Components

I have developed a unique form (material dialog modal) that allows users to create an account. When the user clicks on the Register button, their created account should appear in a dropdown menu without redirecting or reloading the current page. I am facin ...

"Uploading files using FormData append in Angular is not functioning as expected

I'm working on uploading an image to a PHP API using FormData, but I've encountered an issue with the code below: Here is my HTML Code : <input type="file" name="file" id="file" (change)="onFileSelected($eve ...

Executing an external Python script within a Vue application's terminal locally

Hello, I am new to using Vue.js and Firebase. Currently, I am working on creating a user interface for a network intrusion detection system with Vue.js. I have developed a Python script that allows me to send the terminal output to Firebase. Right now, I a ...

Is there a way for me to retrieve the callback parameters?

Can the parameters of the callback function be accessed within the 'outer' function? function f(callback: (par1: string)=>void): void { // Is it possible to access 'par1' here? } ...

Setting the title of a document in Angular 5 using HTML escaped characters

It seems like a simple problem, but I can't seem to find an easy solution. Currently, I am using the Title service to add titles to my documents and everything is working fine. You can check out the documentation here: https://angular.io/guide/set-doc ...

Translate array into object with correct data types (type-specific method)

Welcome In our project, we have implemented attributes support where each attribute acts as a class. These attributes include information on type, optionality, and name. Instead of creating an interface for every entity, my goal is to automate this proces ...

Explain the concept of a static async create method having identical parameters as the constructor

I have a lot of existing classes that require refactoring to utilize an async constructor. Here's an example: class ClassA { constructor(a: number, b: string, c: string) { //... } //... } I've included an async create method ...

Issues with installing the forked version of the npm/Angular 8 package differ from the original installation method

After utilizing git, forking, branching, pull requests, and npm in my standard nodejs projects without any major issues, I encountered an unexpected problem. When trying to Fork an Angular repository and integrate this forked version into my project, I not ...

Encountering issues during the installation of JSNLog

Encountering some challenges with the installation and utilization of jsnlog following the instructions provided on the documentation. Continuously encountering errors when attempting to import or use the library. Attempted importing the library as outlin ...

What steps can be taken to ensure that the requestAnimationFrame function does not redraw the canvas multiple times after a button click?

I am currently working on a project where I am drawing a sin wave on a canvas and adding movement to it. export class CanvasComponent implements OnInit { @ViewChild('canvas', { static: true }) canvas: ElementRef<HTMLCanvasElement>; ...

What could be causing the deployment failure of my Firebase/Postmark email dispatch function?

My Firebase function deployment is encountering an error during execution: "Function failed on loading user code. This is likely due to a bug in the user code." Below is the snippet of the function's code: const postmark = require("po ...

What is the best way to utilize a single component for validating two other components?

I am encountering an issue with my components setup. I have three components in total: GalleryAddComponent, which is used to add a new element, GalleryItemComponent, used to edit an element, and FieldsComponent, the form component utilized by both GalleryA ...

What to do when faced with the Netlify Error "Dependency Installation Failure"?

Having trouble deploying a website created with react and typescript. I keep encountering an error during the initialization phase: https://i.sstatic.net/LNhFJ.png https://i.sstatic.net/w7KTo.png This is all new to me as I just started working with react ...

Guide on bringing in Typescript definition that exports a lone variable

The "@types/dd-trace" library defines a single variable called trace in the type definition for the "dd-trace" library. declare var trace: TraceProxy; export = trace; declare class TraceProxy extends Tracer { /** * Initializes the tracer. This s ...