Display corresponding JSON images of items within an *ngFor loop in Angular

For my latest project, I am using Angular for the front-end and Laravel for the back-end. The issue I'm facing is with displaying images in Angular that are stored in Laravel storage. The image URLs are stored in the database in JSON format like this:

["projects\December2022\ZbgxdJRvkrkaMwErATJE.jpg","projects\December2022\ogyKr0B3ICyqoU5uMhoM.jpg"]

The data records are being displayed correctly but the associated images are not showing up in Angular.

This is a snippet of my component.ts file:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-projects',
  templateUrl: `
  <div *ngFor="let project of data[0]">
            <div class="col-xl-6 col-12">
                        <div class="single-project-info">
                            <div class="item-content">
                                <h3 class="item-title">{{project.title}}</h3>
                                <p>
                                    {{project.details}}
                                </p>
                            </div>
                        </div>
                    </div>
                    <div class="col-xl-6 col-12">
                        <div class="single-project-slider">
                            <div class="carousel">
                             <!-- The images are not showing -->
                                <div class="slide-item" *ngFor="let image of project.images">
                                    <img src="http://localhost:8000/storage/{{image}}" alt="project">
                                </div>
                                
                            </div>
                        </div>
                    </div>
        </div>
`
})
export class ProjectsComponent {
  data:any = [];
  constructor(private http: HttpClient) {
    this.http.get('http://localhost:8000/api/portfolio').subscribe(data => {
      this.data.push(data);
      console.log(this.data);
    },
    error => console.error(error)
    );
  }

}

In my Laravel API controller:

Route::get('/portfolio', [ProjectController::class, 'ng_index']);


public function ng_index() {
        $projects = Project::orderBy('id', 'DESC')->get();

        return response()->json($projects);
    }

The error message I'm receiving for the images is:

Cannot find a differ supporting object

In the console, the request looks something like this:

Array(8)
0: {id: 17, title: 'Carpet & Upholstery Cleaning', slug: 'carpet-and-upholstery-cleaning', images: '["projects\\\\December2022\\\\V…rojects\\\\December2022\\\\sjCz7dBTKxTVoamiZbXP.jpg"]', details: 'Refurbishment of upholstery & carpet in a luxury w… state of the upholstery and carpets in the wing.', …}
1: {id: 15, title: 'Hardwood Finishing', slug: 'hardwood-finishing', images: '["projects\\\\December2022\\\\8G…rojects\\\\December2022\\\\B0JV4G5WYitn66QD5hmU.jpg"]', details: 'Classic hardwood finishing in a residential apartm…ardwood from scratches, stains, and water damage.', …}
2: {id: 14, title: 'Granite & Vinyl Restoration', slug: 'granite-and-vinyl-restoration', images: '[&q…rojects\\\\December2022\\\\nTvOl9J3B3yKiY1uor5f.jpg"]', details: 'Improper sealing had led water to impregnate throu…alt with using chemicals and intensive polishing.', …}
3: {id: 13, title: 'Sandstone Repair', slug: 'sandstone-repair', images: '["projects\\\\Dece…rojects\\\\December2022\\\\cPSRGcBI4MpxVVrlgoEA.jpg"]', details: 'In such close proximity to the water fountain, the…o a standard level, removing the signs of damage.', …}
4: {id: 12, title: 'Marble Finishing', slug: 'marble-finishing', images: '[&…rojects\\\\December2022\\\\O1k1ZUQkAflca0MMGv7u.jpg"]', details: "A quick polish, and color-enhancing treatment popp…e statues visible on the community's front gates.", …}
5: {id: 11, title: 'Marble & Limestone Restoration', slug: 'marble-and-limestone-res…rojects\\\\December2022\\\\BfYVJbEgrYUYjNdk3qz6.jpg"]', details: 'Severe staining and damage caused by improper tile… then filled with putty to get rid of the cracks.', …}
6: {id: 10, title: 'Marble Re-Grouting, Repairing & Polishing', slug: 'marble-re-groutin…rojects\\\\December2022\\\\rEroz19LW7hPc3yehdcC.jpg"]', details: 'Original marble surface lacked quality grout. Some… polished the building lobby to a crystal finish.', …}
7: {id: 9, title: 'Vinyl Re-Finishing', slug: 'vinyl-re-finishing', images: '["projects\\\\Decem…rojects\\\\December2022\\\\ogyKr0B3ICyqoU5uMhoM.jpg"]', details: 'Vinyl tiles were long over-due for re-finishing. O…sh according to the specifications of the client.', …}
length: 8

Answer №1

To ensure proper image paths are sent from the API, consider manipulating them in the front-end service using the following code snippet:

const images = ["projects\\\\January2023\\\\ZWaRtI3fpgODSj0TYLkm.jpg", "projects\\\\January2023\\\\JlYDCRnP84ZIlWEph78r.jpg"];
const newImages = [...images].map(image => image.replaceAll('\\\\', '/'));
console.log("ORIGINAL >>>", images);
console.log("UPDATED >>>", newImages);

Answer №2

Here's a solution that has worked well for me in the past:

@Component({
  selector: 'app-projects',
  templateUrl: './projects.component.html',
  styleUrls: [`
<swiper  *ngFor="let project of data"
  [pagination]="{
  type: 'progressbar'
  }">
  <ng-template swiperSlide  *ngFor="let image of project.images">
    <img [src]="'http://localhost:8000/storage/'+image" alt="">    
  </ng-template>
</swiper>
`]
})
export class ProjectsComponent {
  data:any[] = [];
  constructor(private http: HttpClient) {
  }
  ngOnInit() {
    this.http.get('http://localhost:8000/api/portfolio').subscribe(
      (records: any[0]) => {
        records.forEach((record: any) => {
          record.images = JSON.parse(record.images);
          this.data.push(record);
        });
      },
      error => {
        console.error(error);
      }
    );
  }
}

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

Transform legitimate JSON into a Task<string>

Currently, I am working on mocking ReadAsStringAsync on the first line to be used in a unit test that will result in a Task where the string represents the JSON provided below: var jsonString = await response.Content.ReadAsStringAsync(); // converting it ...

The system is unable to locate a compatible object with the identifier '[object Object]' of type 'object'. NgFor is limited to binding with iterables like Arrays, not JSON data

Working with JSON data data:[ { assets:[[tool_order_id: "38",order_status_id: "10"]], order_info:[id: "1", order_type: "6",check: "1", current_Stage_id: "29"] }, { assets:[tool_order_ ...

It is recommended to place Laravel JavaScript files either in the view or public directories for optimal

When working with a JavaScript that requires a root directory path provided by PHP to call a JSON file, the question arises whether to place the code in public/js or within the template.blade.php file. If the code is placed in public/js, an absolute path ...

Exploring JSON objects within other JSON objects

As I work on my Angular App and implement angular translate for dual language support, I've encountered an issue with accessing nested items within my JSON object. After carefully constructing my JSON and verifying its validity, I attempt to retrieve ...

Steps for reverting the version of angular cli from 1.0.1 to 1.0.0

Hey there, I'm struggling to deploy my app due to the version of angular-cli. After checking, I found that my angular-cli version is: @angular/common: 2.4.10 @angular/compiler: 2.4.10 @angular/core: 2.4.10 @angular/forms: 2.4.10 @angular/http: 2.4.1 ...

What is the reason for the typescript check failing?

When attempting to check for the existence of an attribute using if statement, I encountered an error. Can anyone explain why this happened? I would appreciate any insights on this issue. ...

Searching for suggestions in VueJS 2 using the typeahead callback function

I have integrated the Typeahead component from vue-strap into my project. After selecting an option, I want to trigger a callback function that will populate my input fields with the selected data. The issue I am facing is that while inventoryName and in ...

Retrieve the Json object or iterate through a loop

Looking for assistance with extracting values from a JSON object. Here's the JSON data I have: {"sockets":{"16":true},"length":1} I've attempted to retrieve the socket values using loops and other methods without success. Can anyone provide gui ...

Is TypeScript being converted to JavaScript with both files in the same directory?

As I begin my journey with TypeScript in my new Angular project, I find myself pondering the best approach for organizing all these JS and TS files. Currently, it appears that the transpiler is placing the .js files in the same directory as the correspondi ...

retrieve the router information from a location other than the router-outlet

I have set up my layout as shown below. I would like to have my components (each being a separate route) displayed inside mat-card-content. The issue arises when I try to dynamically change mat-card-title, as it is not within the router-outlet and does not ...

The ng-repeat functionality in Angular 2 is not functioning correctly when trying to select an option from an array of objects. Instead of displaying the actual object, it is

When using ngRepeat in Angular 2, I have found that selecting options from an array of strings works perfectly fine. However, when the data is an array of objects, the ngModel displays '[Object object]' instead of the selected object. I have trie ...

Can you use setValidators() in Angular to validate two patterns simultaneously?

Is there a way to validate both IP address and IP address range in a single control using Angular? I have tried using the following code snippet: controls["CapPoolVolExpolAldClientControl"].setValidators([Validators.required, Validators.pattern(/([0-9]){1 ...

Is it possible to modify JSON data by property name?

Presently, my structure looks like this: List<dynamic> lst = new List<dynamic>(); lst.Add(new{objId = 1,myOtherColumn = 5}); lst.Add(new{objId = 2,myOtherColumn = 6}); lst.Add(new{lala = "asd" ,lala2 = 7}); I'm utilizing the fol ...

Error handling in Python is a critical skill for developers to master

Struggling to parse a valid JSON file but encountering an error. The JSON structure has been validated as well. Error: parseJSON = json.loads(jsonFilePath); File "C:\Python34\lib\json\__init__.py", line 318, in loads return _d ...

javascript monitoring numerous socket channels for echoes

Currently, I am in the process of developing a chat application. On the server side, I am utilizing: php, laravel 5.4, and pusher. On the client side, I have incorporated vue.js along with laravel-echo. Initially, I successfully created a "public chat roo ...

Using Python to convert a data frame into a nested dictionary

Currently, I have a dataframe structured like this: day account_id balance 2022-11-01 ncw8y7 1.000000 2022-11-02 ncw8y7 1.000424 My goal is to convert it into a nested dictionary format where the first level represents the acco ...

Modifying the default login/register URL in Laravel version 5.6

Currently working with Laravel 5.6 and the default Login/register functions are exactly what I need. I successfully eliminated the "/public" from my URL by renaming server.php in the root "myapp" directory to index.php, and then transferring the .htaccess ...

Ways to deliver JSON Array in ASP.NET Web API C#

I need to display a JSON array in the following format on a web browser: { "RainfallAreaAVG": [ { "AreaBbsID": "18", "DistCount": "1", "SubDistCount": "2", "Amount": "14", "Hail": "14", "ArealDetails ...

What is the best way to pass data from a controller to an @include in Laravel?

I have a sidebar named side.balde.php, which is included in the home view and other views using @include. When I return the view side.balde.php with variables/data in my controller, the home view cannot recognize the variables. return view('incs/sid ...

Using jQuery in Jest test with Angular 5: A step-by-step guide

I am facing an issue with my Angular component that utilizes a CalendarService. Upon initialization of the component, I invoke the "calendarService.init()" method. The CalendarService is responsible for configuring a semantic-ui-calendar (which relies on ...