Angular 6: Transform object and add to array

My service includes a method called getCategory() that retrieves categories from the server. The method looks like this:

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

Within my component, I aim to store the retrieved data in an array named categoryList: CategoryModel[]; using the following method:

getCategory(): void {
        this.dataStorageServiceService.getCategory()
            .subscribe(
                (categories: CategoryModel[]) => {
                    this.categoryList = categories;
                    console.log(this.categoryList)
                }
            }

The output of categoryList is displayed as an Object, and unfortunately, I am unable to render it on the template.

Answer №1

If you find yourself receiving an object instead of an array, there are two solutions available. You can either convert your object to an array or utilize the KeyValuePipe in your HTML template -

 <div *ngFor="let category of categoryList | keyvalue">
      {{category.key}}:{{category.value}}
  </div>

To learn more, please visit - https://github.com/angular/angular/blob/master/CHANGELOG.md#610-beta1-2018-06-13

Answer №2

If you're working with Firebase, keep in mind that objects are preferred over arrays. For more information on this best practice, check out this article.

To work around this, one approach is to transform the object into an array when retrieving it from your service:

return this.http.get<CategoryModel[]> (this.productUrl)
  .pipe(
    map(products => {
      return Object.values(products);

      // Alternatively

      return Object.keys(products).map((keyName) => {
        return {id: keyName, product: products[keyName]};
      });
    }),
    catchError(this.handleError('getHeroes', []))
  );

Answer №3

Another option is to utilize the following code snippet:

categoryList : CategoryModel[] = [];

Subsequently, you can add the user object and convert it into an array like this:

this.categoryList.push(<<insert data to be pushed>>);

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

In ES5, this.method does not exist as a function

I am facing an issue with a TypeScript 2 class that targets ES5. When I run it, I receive an error in the console stating that the increment() and decrement() methods do not execute, although the switch statement works fine. class MyClass extends React. ...

Is it possible to utilize a component's property as an argument for a method in Angular 6?

Within my Angular 6 application, I have a method designed to alter a property of my component. The scenario is as follows: ... value: number = 10; changeValue(v) { return v = 100; } ... Upon invoking this method with the component's property: this. ...

A more efficient method for incorporating types into props within a functional component in a TypeScript-enabled NextJS project

When dealing with multiple props, I am looking for a way to add types. For example: export default function Posts({ source, frontMatter }) { ... } I have discovered one method which involves creating a wrapper type first and then defining the parameter ty ...

Leveraging the expand function for pagination through recursive invocations

I am currently working on retrieving data from a third party API that necessitates manual management of paging by keeping track of the number of records retrieved versus the total number of records available. In attempting to handle this, I experimented w ...

Tips for efficiently calling a function without the need to check if it exists beforehand

I'm looking for a way to access the formik props outside of the form without constantly checking if a function exists before calling it when using refs. Any suggestions on how to achieve this? function BasicInfo({ event, initialValues, onSubmi ...

Retrieve the template parameter from a generic type

While I have experience extracting string from string[], this particular scenario is proving to be quite challenging: type example<T = boolean> = true; // with just "example", how can I retrieve the template parameter "boolean" in this case? type T ...

Connect a datetime-local typed input to a Date attribute in Angular 2

Can a property of type Date in a component be bound to an HTML5 input with the type attribute set as datetime-local? For example, I have a component with the following property: public filterDateFrom: Date; And in my template, I am trying to bind this p ...

Button to expand or collapse all sections in Ant Design Collapse component

Is there a way to create a button that can expand or collapse all tabs in an ant.design Collapse component? I attempted to modify defaultActiveKey but it seems like this can only be done during page rendering. If possible, could someone share a code snip ...

guide for dynamically loading angular modules

In my application, I have three modules: home, moduleA, and moduleB. Within my app component, I am making a call to an API called session which returns a value named mode. Depending on the mode being moduleA or moduleB, I need to lazy load the respective m ...

Combining the JSON code coverage reports generated by both Cypress and Karma does not yield an accurate outcome

In my angular project, I am testing it using the built-in unit testing tool (karma) and Cypress. My goal is to combine the code coverage reports from both tests. I have successfully set up the coverage configurations and merged the outputs using `nyc merg ...

Why am I receiving a 404 error when trying to access an Angular 9 route within a subfolder

I am facing an issue with my Angular 9 app that is hosted in a domain subfolder. The problem lies in the index.html base tag, shown below: <base href="/subfolder/"> Everything works perfectly fine when the app is run locally without the ba ...

Unable to modify the SVG color until it has been inserted into a canvas element

There is an SVG code that cannot be modified: <?xml version="1.0" encoding="UTF-8"?> <svg id="shape" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"> <path d="M29.57,19.75l-3. ...

The type x cannot be assigned to the parameter '{ x: any; }'

Currently learning Angular and Typescript but encountering an error. It seems to be related to specifying the type, but I'm unsure of the exact issue. Still new at this, so any guidance is appreciated! src/app/shopping-list-new/shopping-edit/shopp ...

What is the reason behind using `Partial<>` to enclose the Vue props?

I am currently working with a combination of technologies, and I am struggling to pinpoint the root cause of the issue. Here is the Tech Stack: Vue 3 TypeScript Vite VSCode / Volar unplugin-vue-macros (https://github.com/sxzz/vue-macros) unplugin-vue-com ...

Excluding generated js and js.map files from TFS in .Net Core and Typescript

I'm currently working on a .NET Core project and looking to integrate TypeScript into it. However, I am encountering issues with excluding the generated .js and .js.map files from being included in check-ins. After attempting the tfignore method ment ...

What is the correct method for integrating jQuery libraries into an Angular project version 10 or higher?

Currently, I am facing difficulties while attempting to install the jquery and jquery-slimscroll packages into an Angular project (version greater than 10). It appears that the installation of these packages has not been successful. In light of this issue, ...

New Entry failing to appear in table after new record is inserted in CRUD Angular application

Working with Angular 13, I developed a basic CRUD application for managing employee data. Upon submitting new information, the createEmployee() service is executed and the data is displayed in the console. However, sometimes the newly created entry does no ...

Guide on deploying multiple applications under a single URL with S3 on Amazon Web Services

I am working on deploying multiple Angular and React apps on AWS through S3. Currently, one of my Angular apps is successfully running when accessing mysite.com. It functions properly as intended. I am looking for a way to load different apps based on th ...

What is the correct way to effectively share data between components using a service?

I've been diving into learning Angular 2 and successfully implemented data sharing between sibling components using input/output functions. Check out my working example here. // Our root app component import {Component, NgModule} from '@angular ...

Loading dynamic content within Angular Material tabs allows for a more customized and interactive user experience

I am currently working on creating a dynamic tab system using Angular Material: Tabs. I have encountered an issue with loading content on tabs after the initial one, where the functionality only works when the first tab is loaded. Below you can see the ta ...