Obtain JSON information in a structured model layout using Angular 4

I have different categories in the backend and I would like to retrieve them in a model format. Here is how my model is structured:

export class Category {
name: string;
id : string;
}

And this is how the data appears in the backend:

{
 "name": "cars",
 "id": "5a082ab8cb2b3f6b373e3042"
}

Below is the code for my service:

import { Category } from '../../core/models/category.model';
@Injectable()
export class CategoryService {

constructor(private _http: HttpClient) { }

fetchCategory() 
    {
    return this._http.get<Category>(environment.apiPath+"categories");
      }

  }

Here is my component code:

import { Category } from '../../core/models/category.model';
@Component({
 selector: 'app-barter-view',
 templateUrl: './barter-view.component.html',
 styleUrls: ['./barter-view.component.css'],
 providers:[CategoryService]
})
export class BarterViewComponent implements OnInit {
allCategories :Category ;
constructor(private cact: CategoryService){}
ngOnInit() {
  this.cact.fetchCategory() .subscribe(response=> {
    console.log(response)
    this.allCategories=response 
    }
 );
}

Check out the console output here.

Answer №1

Consider using an interface when defining the type of your result:

export interface Product {
 name: string;
 id : number;
}

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

What causes a BehaviorSubject to update when modifying the [(NgModel)] values of a form without actually submitting the form?

When I work with a form that relies on a BehaviorSubject to load user information, I noticed that if I make changes to the inputs but navigate away from the page without submitting the form, the user information gets updated in the subject automatically. ...

I am facing an issue with my interface - the variable designed to store boolean values

Something unusual happened with Typescript - I assigned a string value to a boolean variable, but no error was generated. I purposely triggered an error in order to observe how Typescript would react, only to find that it did not produce the expected erro ...

Issues with Ionic 3 Directive Not Functioning

Struggling to create a custom directive in Ionic that won't resize automatically? I can't figure out what's going wrong. Here's the code snippet from my project, which is an Ionic 3 app with Angular 4: import { Directive, HostListener ...

Conditional generic type in return type with Typescript

How can I condition the generic return type when a value is not present? type Foo = {}; class Bar<P extends Foo> { static make<P extends Foo>(a?: P): Bar<P> { return new Bar(); } } Bar.make() // returns Bar<Foo> ...

Guide for sorting Material Table does not work as expected

Hello everyone! I've been working on implementing the guidelines provided at https://material.angular.io/components/table/overview I'm currently facing an issue with sorting my table. When I click on the table headers, nothing happens. Can anyon ...

Can the router accommodate multiple loadChildrens at once?

I recently upgraded to the latest version of angular 2 and discovered an interesting lazy load feature utilizing loadChildren. Let me illustrate with a simple example export const routes: Routes = [ { path: 'crisis', loadChildren: 'app/c ...

Make sure to verify the optional parameter before using it in your code

Is it possible for TypeScript compiler to detect errors in code such as this, with certain tsconfig rules in place? function buildName(firstName: string, lastName?: string) { return firstName + " " + lastName; } I believe that if there is no c ...

Why does the "revalidate" field in Incremental Static Regeneration keep refreshing without considering the specified delay?

I am currently referencing the guidance provided at: https://nextjs.org/docs/basic-features/data-fetching/incremental-static-regeneration. My intention when setting the revalidate: 60 * 10 parameter is: To have the content remain consistent for at least ...

What is the best way to extract a specific property from an object?

Consider the following function: getNewColor(): {} { return colors.red; } Along with this object: colors: any = { red: {primary: '#ad2121',secondary: '#FAE3E3'}, blue: {primary: '#1e90ff',secondary: '#D1E8FF&apos ...

Discover the process of dynamically importing JavaScript libraries, modules, and non-component elements within a Next.js

Lately, I have been utilizing Next.js and mastering its dynamic import feature for importing components with named exports. However, I recently encountered a particular npm package that functions only on the client-side (requires window) and has a substant ...

"Enhancing User Experience: Implementing Internationalization and Nested Layouts in Next.js 13.x

In the midst of working on a cutting-edge Next.js 13 project that utilizes the new /app folder routing, I am delving into the realm of setting up internationalization. Within my project's structure, it is organized as follows: https://i.stack.imgur.c ...

Designate as a customizable class property

I'm struggling to create a versatile inheritance class for my services. Currently, I have two service classes named Service_A and Service_B that essentially do the same thing. However, Service_A works with Class_A while Service_B works with Class_B. T ...

Tips for creating a window closing event handler in Angular 2

Can someone guide me on how to create a window closing event handler in Angular 2, specifically for closing and not refreshing the page? I am unable to use window.onBeforeunLoad(); method. ...

Error in TypeScript when utilizing an Enum as a string

Attempting to include a string enum in my Angular 2 project resulted in an error during the npm project startup: ERROR in e:/projects/dbtool-fullstack/dbtool-client/src/app/shared/models/full-m odels/enums/Sex.ts (2,10): Type '"Male"' is not ass ...

Navigating through different components within a single page

Each segment of my webpage is a distinct component, arranged consecutively while scrolling e.g.: <sectionA></sectionA> <sectionB></sectionB> <sectionC></sectionC> All the examples I've come across involve creating ...

Having difficulty sending the [ctrl][p] keys to a page that is not using Angular framework

Working with protractor version 5.1.2, Angular 5, and typescript 2.4.2 When attempting to trigger a 'print' function using the shortcut keys '[ctrl][p]' in protractor on a non-angular page, I encountered an issue. Within my protractor ...

Displaying an Array in HTML using Angular

Just starting out with Angular and experimenting with data display from an array. The data in the array is: [Me, Three, Four] I attempted to loop through it for printing but encountered issues. Here's a snippet of how I'm currently handling it: ...

Looking to merge two components into one single form using Angular?

I am currently developing an Angular application with a dynamic form feature. The data for the dynamic form is loaded through JSON, which is divided into two parts: part 1 and part 2. // JSON Data Part 1 jsonDataPart1: any = [ { "e ...

Tips for assigning types from an interface object in TypeScript

Here is the code snippet I'm dealing with interface deviceInfo { Data: { model: string; year: number; }; } const gadget: deviceInfo.Data; I encountered a warning in vscode that indicates there ...

What is the best way to utilize "exports" in package.json for TypeScript and nested submodules?

Looking to leverage the relatively new "exports" functionality in Node.js/package.json for the following setup: "exports": { ".": "./dist/index.js", "./foo": "./dist/path/to/foo.js" } so that ...