Navid
Navid

Reputation: 45

How To Gather the Data In Angular Received From WebApi

I'm new in programming specially in angular and I'd appreciate it if someone help me with my code, please.

A brief explanation of what I'm trying to do as a practice is:

Getting images from the web api in angular project.

Web API side:

Controller:

   [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class HomeController : ApiController
    {
        private NavEcommerceDBfirstEntities db = new NavEcommerceDBfirstEntities();
        public HomeModel Get()
        {
            var streetBikes = db.Motorcycles
                .Where(m => m.Category.MotoCategory == "Street")
                .Select(m => new MotorcycleImgDTO
                {
                    Image = m.Image
                });
            var sportBikes = db.Motorcycles
                .Where(m => m.Category.MotoCategory == "Sport")
                .Select(m => new MotorcycleImgDTO
                {
                    Image = m.Image
                });
            var adventureBikes = db.Motorcycles
                .Where(m => m.Category.MotoCategory == "Adventure")
                .Select(m => new MotorcycleImgDTO
                {
                    Image = m.Image
                });
            var scooterBikes = db.Motorcycles
                .Where(m => m.Category.MotoCategory == "Scooter")
                .Select(m => new MotorcycleImgDTO
                {
                    Image = m.Image
                });
            var homeModel = new HomeModel
            {
                SportBikes = sportBikes,
                StreetBikes = streetBikes,
                AdventureBikes = adventureBikes,
                ScooterBikes = scooterBikes
            };

            return homeModel;
        }

    }

Models:

HomeModel class:

    public class HomeModel
    {
        public IEnumerable<MotorcycleImgDTO> StreetBikes { get; set; }
        public IEnumerable<MotorcycleImgDTO> SportBikes { get; set; }
        public IEnumerable<MotorcycleImgDTO> AdventureBikes { get; set; }
        public IEnumerable<MotorcycleImgDTO> ScooterBikes { get; set; }

    }

Motorcycle class:

//Database First Approach and Created by ADO.NET 
    public partial class Motorcycle
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Motorcycle()
        {
            this.Carts = new HashSet<Cart>();
            this.OrderDetails = new HashSet<OrderDetail>();
            this.Dealers = new HashSet<Dealer>();
        }
    
        public int MotorcycleId { get; set; }
        public string Model { get; set; }
        public double Price { get; set; }
        public Nullable<int> BrandId { get; set; }
        public byte[] Image { get; set; }
        public Nullable<int> CategoryId { get; set; }
    
        public virtual Brand Brand { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Cart> Carts { get; set; }
        public virtual Category Category { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<OrderDetail> OrderDetails { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Dealer> Dealers { get; set; }
    }

DTO class:

    public class MotorcycleImgDTO
    {
        public byte[] Image { get; set; }

    }

Angular Side:

Model:

home-categorised-bikes.model.ts:

export interface FromDTOImgs{
    image: Byte[];
}

export interface HomeModel{
SportBikes: FromDTOImgs[];
StreetBikes: FromDTOImgs[]; 
AdventureBikes: FromDTOImgs[];
ScooterBikes: FromDTOImgs[];
}

Service:

home-categorised-bikes.service.ts:

@Injectable({
  providedIn: 'root'
})
export class HomeCategorisedBikesService {

  imageUrl = 'https://localhost:44377/api/Home';

  constructor(private http: HttpClient) { }

  getImg(): Observable<BikesImg[]> {
    return this.http.get<BikesImg[]>(this.imageUrl);
  }
}

app.component.ts:

import { Component, OnInit } from '@angular/core';
import { HomeCategorisedBikesService } from './services/home-categorised-bikes.service';
import{HomeModel} from './models/home-categorised-bikes.model';

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

  constructor(private homeCategorisedBikesService: HomeCategorisedBikesService){}

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

getAllBikesImgs(){
this.homeCategorisedBikesService.getImg().subscribe(
  Response => {
    this.onHomeBikesImgsResponse(Response);
    console.log(Response);
  }  
)
}
public bikesImgs: string[] = [];
private onHomeBikesImgsResponse(Response: HomeModel[]): void {
Response.forEach((bikeImg: HomeModel) => {
  this.bikesImgs.push(`data:image/png;base64,${bikeImg.SportBikes}`);
});
}
}

app.component.html:

<div class="container">
    <h4>{{title}}</h4>

    <div *ngFor="let bikeImg of bikesImgs">
        <img [src]="bikeImg">
    </div>

Swagger:

Swagger response

Question:

Currently I'm getting an error in angular.

How to fix the angular side to get the images to be able to display them into the browser ?

Error:

(parameter) Response: FromDTOImgs[] Argument of type 'FromDTOImgs[]' is not assignable to parameter of type 'HomeModel[]'. Type 'FromDTOImgs' is missing the following properties from type 'HomeModel': SportBikes, StreetBikes, AdventureBikes, ScooterBikes

Thank you in advance.

Upvotes: 1

Views: 54

Answers (1)

Markus
Markus

Reputation: 22456

You describe two separate problems:

The status code 404 (NotFound) means that the URL that Angular used cannot be mapped to a controller action of the ASP.NET Core API. So you need to check if the URL that Angular uses is correct.

As for the "not assignable" error: the method onHomeBikesImgsResponse expects a parameter of type HomeModel[], but the service delivers BikesImg[]. Most likely, this is due to paste and copy. I think you can use BikesImg[] as the parameter type of onHomeBikesImgsResponse.

Upvotes: 1

Related Questions