Search code examples
asp.netangular

How to display image received by a Web API on Angular


I have an image that the image data's coming from database through the web api. This image's path saves in DB's imagePath column. However when I call this data via the web api I onle get this path value. So if I want to show an image with that path I will exactly get 404 error. The point that I don't understand how to show this image on UI. Angular is working on different port and the backend also working on different port. If I get the images by using backend url/port it wouldn't good in terms of seo. How can I solve this problem?

I am using C# & .Net Core 3.1 and Asp.Net Web Api on the backend.

Car Component Codes

getCars(){
this.carService.getCars().subscribe(response => {
  this.cars = response.data;
  this.dataLoaded = true;
  this.setCoverImage(this.cars);
});
}  
getCarImages(){
      this.carImageService.getCarImages().subscribe(response => {
          this.carImages = response.data;
        })
      }


 setCoverImage(carList: Car[]){
     carList.forEach(item => {
       this.carImageService.getCarImagesById(item.carId).subscribe(response => {
         item.imagePath = "http://localhost:4200/" + response.data[0].imagePath;
       })
      })
    }

Car Image Service Codes

export class CarImageService {
  apiUrl = "https://localhost:44327/api/";
  constructor(private httpClient : HttpClient) { }

  getCarImages() : Observable<ListResponseModel<CarImage>>{
    let newPath = this.apiUrl + "carimages/getall";
    return this.httpClient.get<ListResponseModel<CarImage>>(newPath);
  }

  getCarImagesById(carId: number) : Observable<ListResponseModel<CarImage>>{
    let newPath = this.apiUrl + "carimages/getimagesbycarid?id=" + carId;
    return this.httpClient.get<ListResponseModel<CarImage>>(newPath);
  } 
}

API output


Solution

  • You can use proxy in your client app.

    Example from my project :

    {
      "context": [ "/images" ], 
      "target" : "http://localhost:5000", 
      "secure": false, 
      "changeOrigin": true, 
      "logLevel": "debug"
    }
    

    With this json proxy configuration I can get files from images folder which is at wwwroot directory.