Here is a guide on showcasing information obtained from ASP.NET API in Angular version 13

My goal is to fetch motorcycle data from a web API and showcase it in my Angular project.

  • ASP.NET Framework Web API 4.7
  • Angular CLI: 13.3.7
  • Angular: 13.3.11

On the Web API end:

Controller:


    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class HomeController : ApiController
    {
        private NavEcommerceDBfirstEntities db = new NavEcommerceDBfirstEntities();

        public HomeModel Get()
        {

        var streetBikesContents = db.Motorcycles.Where(m => m.Category.MotoCategory == "Street").Select(m => new MotorcycleDTO
            {
                 ModelDto = m.Model,
                PriceDto = m.Price,
                BrandDto = m.Brand.Name,
                CategoryDto = m.Category.MotoCategory,
                DealersDto = m.Dealers.Select(d => d.Name).ToList()
            });

            // The rest of the code remains the same...

            return homeModel;
        }

    }
}

    }

Models:

app.component.ts:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'Home Page';

  constructor(private homeCategorisedBikesService: HomeCategorisedBikesService){}

ngOnInit(): void {
  this.getAllBikesContents();
}

// Further implementation for fetching bike contents...

} 

app.component.html:

Question:

I aim to showcase various details of each motorcycle such as model, brand, category, price, and dealers' array individually. Kindly provide feedback on any unclear areas within the code or question.

Thank you in advance.

Answer №1

If you declare your variable as sportBikesContentsvar and others, you may encounter issues. It's recommended to define your object type as FromDTOContents[].

By doing this, you will have access to all the properties of the object.

I'll provide an example below, but the rest will follow the same pattern:

public sportBikesContentsvar: FromDTOContents[] = [];

onHomeBikesContentsResponse(Response: HomeModel): void {
  this.sportBikesContentsvar = Response.sportBikesContents;
}

Then in the HTML portion:

<div class="container">
    <h3 class="textCenter">Sport Bikes</h3>
    <div class="column" *ngFor="let c of sportBikesContentsvar">
        <h3>{{c.ModelDto}}</h3>
        <h3>{{c.PriceDto}}</h3>
        <h3>{{c.BrandDto}}</h3>
        <h3>{{c.CategoryDto}}</h3>
        <ng-container *ngFor="let dealers of c.DealersDto">
           <h3>{{dealers}}</h3>
        </ng-container>
    </div>
</div>

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

The connection between Cognito identity and Mqtt is not possible within AWS IoT Core

The application is built using Angular. Upon logging in with Cognito, the application retrieves the user's CognitoUser data, including id token, access key, and session token. Next, the application connects to Iot Core to subscribe to or publish data ...

Dealing with null values sent from a WCF service in the client application

Utilizing a WCF Service, I have incorporated AJAX to invoke the service methods from my web application. The AJAX call is structured as follows: $.ajax({ type: 'GET', url: 'http://localhost:56083/Service1.svc/Web/Get ...

Testing the Snackbar function with Angular and TypeScript: Unit Testing

I've encountered an issue with a method called onDelete that utilizes a MatSnackBar which is injected in the constructor like so: constructor(private todoListService: TodolistService, private snackBar: MatSnackBar) { } onDelete(todoList: TodoList): v ...

What methods can be used in Angular 2 to delete and update row data through HTTP calls?

I am currently working on implementing employee data manipulation functionalities in an Angular application. While I have successfully managed to add new data to the array, I am facing challenges with updating and deleting existing data. Could someone pro ...

What is the best way to access the download path in browser preferences?

In my C# code, I am using Selenium to perform tests that involve file downloads. While I can successfully download files in my tests, I am facing issues with verifying the success of the downloads. As a solution, I want to retrieve the current download pat ...

Searching for a streamlined approach to retrieve a segment of a string

I'm currently working with JavaScript and TypeScript. Within my code, I encountered a scenario where I have a string that might contain certain tags indicating importance or urgency. Here are a couple of examples: A: "Remind me to go to the store to ...

Returns false: CanActivate Observable detects a delay during service validation

Issue with Route Guard in Angular Application: I encountered an issue with my route guard in my Angular application. The problem arises when the guard is active and runs a check by calling a service to retrieve a value. This value is then mapped to true or ...

How to extract the names of fields without sub-field names in JSON for C#?

Can you show me the proper way to define a C# class (or classes) using Json.net (Newtonsoft.json) for handling the json structure provided below? The 'data' field seems to consist of level/description sub-fields without any preceding field names ...

Update the TemplateUrl according to the URL Parameters (GET)

I've created a basic Angular code snippet (test.component.ts) that retrieves a variable from GET parameters: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ select ...

Why has the phrase "The current context does not contain the name 'ScreenshotImageFormat'" become obsolete?

Each month, I have a program that I use to test various website pages using Selenium testing. Afterwards, I upload the screenshots of the output to a specific location. This time, unexpectedly, the program encountered an error and suggested that I run the ...

Experiencing unfamiliar typescript glitches while attempting to compile a turborepo initiative

I have been utilizing the turborepo-template for my project. Initially, everything was running smoothly until TypeScript suddenly started displaying peculiar errors. ../../packages/fork-me/src/client/star-me/star-me.tsx:19:4 nextjs-example:build: Type erro ...

Exploring Angular: A Guide to Importing Material Components

Trying to incorporate elements such as sliders and tooltips into my project, but encountering issues with imports. I've experimented with adding the import statement for MatSliderModule in various locations like app.module.ts and specific component mo ...

Transferring data types to a component and then sending it to a factory

I have been grappling with creating a factory method using Angular 2 and TypeScript. However, my attempts have hit a roadblock as the TSC compiler keeps throwing an unexpected error: error TS1005: ',' expected. The issue arises when I try to pa ...

Preventing child element clicks in Angular 5: A helpful guide

I have checked numerous references, but unfortunately haven't received any responses. That's why I have turned to this platform in hopes of improving my code with your assistance. I need to add an element with text on click. Currently, it works ...

Asynchronous data binding in Angular 2

I'm trying to pass a value from my ImageDetail component to the ImageComment component as follows: ImageDetailHtml: <image-comment [photo]="photo"></image-comment> ImageCommentComponent: export class ImageCommentComponent { @Input(&a ...

Setting up popover functionality in TypeScript with Bootstrap 4

Seeking assistance with initializing popovers using TypeScript. I am attempting to initialize each element with the data-toggle="popover" attribute found on the page using querySelectorAll(). Here is an example of what I have tried so far: export class P ...

Pass an array of objects to an Angular 8 component for rendering

Recently, I started working with Angular 8 and faced an issue while trying to pass an array of objects to my component for displaying it in the UI. parent-component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: ...

Identify numbers and words within a sentence and store them in an array

Looking to split a string into an array based on type, extracting numbers and floats. The current code is able to extract some values but not complete. var arr = "this is a string 5.86 x10‘9/l 1.90 7.00" .match(/\d+\.\d+|\d+&bsol ...

What is the correct way to specify an image path for a background URL?

Currently, I am setting a background image for the hr tag using the following code: <hr style="height:6px;background: url(http://ibrahimjabbari.com/english/images/hr-11.png) repeat-x 0 0;border: 0;margin:0px!important"> However, I have now saved th ...

Consolidate various arrays of objects while eliminating duplicate items based on an optional property

Imagine having multiple arrays like these: const arr1 = [ { "id": "1", "type": "sales" }, { "id": "2", "type": "finance" } ] const arr2 = [ { "type": "s ...