简体   繁体   English

如何在 Angular 中收集从 WebApi 接收的数据

[英]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.从 Angular 项目中的 web api 获取图像。

  • ASP.NET Framework Web API 4.7 ASP.NET 框架 Web API 4.7
  • Angular CLI: 13.3.7角 CLI:13.3.7
  • Angular: 13.3.11角度:13.3.11

Web API side: Web API 端:

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: DTO类:

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

    }

Angular Side:角边:

Model:模型:

home-categorised-bikes.model.ts:家庭分类自行车.model.ts:

export interface FromDTOImgs{
    image: Byte[];
}

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

Service:服务:

home-categorised-bikes.service.ts:家庭分类自行车.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: 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: app.component.html:

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

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

Swagger:昂首阔步:

大摇大摆的回应

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[]'. (参数)响应:FromDTOImgs[] 类型“FromDTOImgs[]”的参数不可分配给“HomeModel[]”类型的参数。 Type 'FromDTOImgs' is missing the following properties from type 'HomeModel': SportBikes, StreetBikes, AdventureBikes, ScooterBikes “FromDTOImgs”类型缺少“HomeModel”类型的以下属性:SportBikes、StreetBikes、AdventureBikes、ScooterBikes

Thank you in advance.先感谢您。

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.状态码 404 (NotFound) 表示 Angular 使用的 URL 无法映射到 ASP.NET Core API 的控制器操作。 So you need to check if the URL that Angular uses is correct.所以你需要检查 Angular 使用的 URL 是否正确。

As for the "not assignable" error: the method onHomeBikesImgsResponse expects a parameter of type HomeModel[] , but the service delivers BikesImg[] .至于“不可分配”错误:方法onHomeBikesImgsResponse需要一个HomeModel[]类型的参数,但服务提供BikesImg[] Most likely, this is due to paste and copy.这很可能是由于粘贴和复制造成的。 I think you can use BikesImg[] as the parameter type of onHomeBikesImgsResponse .我认为您可以使用BikesImg[]作为onHomeBikesImgsResponse的参数类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM