响应。foreach不是一个功能

发布于 2025-02-13 02:15:03 字数 5914 浏览 1 评论 0原文

我是新手的编程,尤其是在Angular上,如果有人帮助我使用代码,我将不胜感激。

我正在尝试从Angular项目中的Web API获取一些图像。

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

Web API侧:

控制器:

[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;
    }

}

模型:

homemodel类:

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; }

}

摩托车类:

//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班级:

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

角侧:

型号:

home-categorized-bikes.model.ts:

export interface FromDTOImgs{
    image: Byte[];
}

export interface HomeModel{
  sportBikes: FromDTOImgs[];
  streetBikes: FromDTOImgs[]; 
  adventureBikes: FromDTOImgs[];
  scooterBikes: FromDTOImgs[];
}

服务:

home-categorisis-bikes.service.ts:

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

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

  constructor(private http: HttpClient) { }

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

app.component.ts:

@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((img: HomeModel) => {
      this.bikesImgs.push(`data:image/png;base64,${img.sportBikes}`);
      this.bikesImgs.push(`data:image/png;base64,${img.streetBikes}`);
      this.bikesImgs.push(`data:image/png;base64,${img.adventureBikes}`);
      this.bikesImgs.push(`data:image/png;base64,${img.scooterBikes}`);
    });
  }
}

app.component.html:

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

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

swagger:

“

错误:

响应。方向不是功能 在appcomponent.onhomebikesimgsresponse(app.component.ts)

请提前感谢您。

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

I'm trying to get some images from a web API in the angular project.

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

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<HomeModel[]> {
    return this.http.get<HomeModel[]>(this.imageUrl);
  }
}

app.component.ts:

@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((img: HomeModel) => {
      this.bikesImgs.push(`data:image/png;base64,${img.sportBikes}`);
      this.bikesImgs.push(`data:image/png;base64,${img.streetBikes}`);
      this.bikesImgs.push(`data:image/png;base64,${img.adventureBikes}`);
      this.bikesImgs.push(`data:image/png;base64,${img.scooterBikes}`);
    });
  }
}

app.component.html:

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

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

Swagger:

Swagger response

Error:

Response.forEach is not a function
at AppComponent.onHomeBikesImgsResponse (app.component.ts)

Thank you in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

乖乖 2025-02-20 02:15:03

正如您可以在自己的Swagger屏幕截图中看到的那样,您的响应不是数组,它是对象Streetbikessportsbikes ....数组。

要循环遍历每个属性并创建一个所有自行车图像的单个数组,您需要这样的东西:

private onHomeBikesImgsResponse(Response: any): void {
  for (const prop in Response) {
    Response[prop].forEach((item: FromDTOImgs) => {
      this.bikesImgs.push(`data:image/png;base64,${item.image}`);
  });
}

As you can see in your own swagger screenshot, your response in not an array, it's a list of objects streetBikes, sportBikes.... Each of those objects are list of arrays.

To loop through each property and to create one single array of all bike images, you need something like this:

private onHomeBikesImgsResponse(Response: any): void {
  for (const prop in Response) {
    Response[prop].forEach((item: FromDTOImgs) => {
      this.bikesImgs.push(`data:image/png;base64,${item.image}`);
  });
}

恍梦境° 2025-02-20 02:15:03

您的API返回带有HomeModel类型的响应,但不是homememodel array。

家庭属性自行车。Service.ts:

export class HomeCategorisedBikesService {

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

  constructor(private http: HttpClient) { }

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

app.component.ts:

private onHomeBikesImgsResponse(Response: HomeModel): void {
  Response.sportBikes.forEach((img: FromDTOImgs) => {
    this.bikesImgs.push(`data:image/png;base64,${img.image}`);
  });

  Response.streetBikes.forEach((img: FromDTOImgs) => {
    this.bikesImgs.push(`data:image/png;base64,${img.image}`);
  });

  Response.adventureBikes.forEach((img: FromDTOImgs) => {
    this.bikesImgs.push(`data:image/png;base64,${img.image}`);
  });

  Response.scooterBikes.forEach((img: FromDTOImgs) => {
    this.bikesImgs.push(`data:image/png;base64,${img.image}`);
  });
}

Your API returns response with HomeModel type, but not HomeModel array.

home-categorised-bikes.service.ts:

export class HomeCategorisedBikesService {

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

  constructor(private http: HttpClient) { }

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

app.component.ts:

private onHomeBikesImgsResponse(Response: HomeModel): void {
  Response.sportBikes.forEach((img: FromDTOImgs) => {
    this.bikesImgs.push(`data:image/png;base64,${img.image}`);
  });

  Response.streetBikes.forEach((img: FromDTOImgs) => {
    this.bikesImgs.push(`data:image/png;base64,${img.image}`);
  });

  Response.adventureBikes.forEach((img: FromDTOImgs) => {
    this.bikesImgs.push(`data:image/png;base64,${img.image}`);
  });

  Response.scooterBikes.forEach((img: FromDTOImgs) => {
    this.bikesImgs.push(`data:image/png;base64,${img.image}`);
  });
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文