What is the best method for retrieving images from a GET request and displaying them in a gallery within an Angular 10 application using ng

Struggling with a difficult code method to import images from an API directly into a gallery or lightbox... Unfortunately, I couldn't find any helpful tutorials, but stumbled upon this example:

https://stackblitz.com/edit/ngx-gallery-imageviewer

After attempting to adapt it to my own code, I successfully retrieved images in arrays, but I'm stuck on how to pass them to a property similar to the one used by the developer in the example.

I am currently at a roadblock where I need to pass my images to a variable with specific properties:

https://i.sstatic.net/ywzXW.jpg

This is the snippet of my code:

 allImages: PostG[] = [];

fetch(this.apiKey)
  .then(response => {
    if (response.ok) {
      return response.json();
    };
  })
  .then((j: any) => {
   
    const image = [...j.data.post.map(item => item.images)];
    
    image.forEach((image: PostG[]) => {
      var obj = {
        image:image,
      }
      this.allImages = [...image];
  return{
        type: "imageViewer",
        imagesGallery: {
        srcUrl: console.log(this.allImages),
        previewUrl: console.log(this.allImages)
      }
    }
  });
});

The current output of this code is displayed below.

https://i.sstatic.net/6eEXm.jpg

If you take a look at the stackblitz example, you'll see that local images are used. In my case, how can I effectively incorporate my photos? I aim to *ngFor every gallery for each post obtained with their respective images.

Here's the HTML implementation I've attempted:

<ion-col class="ion-no-padding" size-md="12" size-lg="12" size-sm="12" size-xs="12" *ngFor="let post of allPosts | sortPipe"> 

//followed by embedding the gallery:

<div class="basic-container">
    <h2>Basic Example</h2>
    <gallery id="basic-test" fluid [items]="items" [itemTemplate]="itemTemplate" [gestures]="false"></gallery>
  </div>

  <!-- create a template to use the imageviewer -->
  <ng-template #itemTemplate let-index="index" let-type="type" let-data="{{this.allImages}}" let-currIndex="currIndex">
    <ng-container *ngIf="type === 'imageViewer' && index === currIndex" >
      <ngx-imageviewer [src]="this.allImages"></ngx-imageviewer>
    </ng-container>
  </ng-template>

Please bear with me if this question seems lengthy, I want to provide all necessary information for your assistance. This project holds great importance for me. Thank you!

Answer №1

To properly format your response as JSON for use with ngx-gallery, follow these steps.

For a more detailed explanation, refer to this tutorial.

I have reproduced the same issue you are currently experiencing

Consider implementing something similar to the following:

this.response.data.posts.forEach(post => {
  post.galleryImages = post.images.map(image => {
    return new ImageItem({ src: image, thumb: image });
  });
});

Once you have created the JSON structure in your HTML file,

<div class="custom-container" *ngFor="let post of response.data.posts; let i=index">
    <h2>{{post.title}}</h2>
    <p>{{post.description}}</p>
    <gallery id="custom-test_{{i}}" fluid [items]="post.galleryImages" [gestures]="false">
    </gallery>
</div>

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

Identify numbers and words within a sentence and store them in an array

Looking to split a string into an array based on type, extracting numbers and floats. The current code is able to extract some values but not complete. var arr = "this is a string 5.86 x10‘9/l 1.90 7.00" .match(/\d+\.\d+|\d+&bsol ...

Calculating different percentages from a reduced map containing JSON data

Forgive me in advance if there's a similar question out there, but after a day of searching, I couldn't find what I need. I'm calling an API that responds with data, and I've extracted the necessary details to create a JSON file with t ...

The Relationship between Field and Parameter Types in TypeScript

I am currently working on a versatile component that allows for the creation of tables based on column configurations. Each row in the table is represented by a specific data model: export interface Record { attribute1: string, attribute2: { subAt ...

What is the rationale behind allowing conflicting types in intersection types?

When presented with two interfaces containing conflicting member types: interface A { x: number } interface B { x: string } It becomes impossible to create an interface that extends both: interface I extends A, B // error TS2320: Interface 'I' ...

Error: "Oops! The [test] view could not be located." Trace: [{file: vendorlaravelframeworksrcIlluminateViewFileViewFinder.php"

I created a web application using Laravel-5.8 for the backend and Angular-7 for the frontend, which includes functionality to send emails through Gmail. .env MAIL_DRIVER = smtp MAIL_HOST = smtp.gmail.com MAIL_PORT = 465 MAIL_USERNAME = <a href="/cdn-c ...

"Utilizing the `useState` function within a `Pressable

Experiencing some unusual behavior that I can't quite figure out. I have a basic form with a submit button, and as I type into the input boxes, I can see the state updating correctly. However, when I click the button, it seems to come out as reset. Th ...

Minimize the reliance on Jquery within Angular 2 applications

In my Angular 2 component, I utilize TypeScript for writing modules. The code snippet below displays my use of Jquery to access the DOM at a certain level. Is this practice recommended in Angular 2? Could someone please explain the pros and cons of integra ...

Using Angular with Cordova - How to troubleshoot using TypeScript files?

Currently in the process of debugging the application using source files written in Typescript. Despite attempting to debug with Chrome, I have been limited to only being able to debug the Javascript files generated by Cordova which has proven difficult. ...

Invalidity of types occurs when dispatching data to redux

My reducer code is as follows: import { profileAPI } from '../api/api' import shortid from 'shortid' const ADD_POST = 'profile/ADD-POST' const SET_USER_PROFILE = 'profile/SET_USER_PROFILE' const SET_STATUS = 'p ...

Using Angular and PrimeNG to easily clear sorting and filtering on a specific column in a datatable (unlike table.reset() which resets all sorting and filtering on the table)

I have a situation where the code provided below is functioning, however, it resets all datatable filters and sorting. My goal is to specifically reset the sorting and filtering for only the 'name' column. In other words, if another column is sor ...

Storing a value received from an observable into a component variable in Angular 4 using the subscribe method

I am attempting to save the value from an observable into a variable within the component by utilizing a service. However, the variable always ends up as undefined. When I check "names" inside the subscribe function, it does contain the expected value. ...

Encountering an unanticipated DOMException after transitioning to Angular 13

My Angular project is utilizing Bootstrap 4.6.2. One of the components features a table with ngb-accordion, which was functioning properly until I upgraded the project to Angular 13. Upon accessing the page containing the accordion in Angular 13, I encount ...

Ways to retrieve a URL from the assets folder

I need to establish a baseUrl for my backend requests within the assets folder. For this, I have created a server configuration file named config.json { "backendServer": { "protocol": "http", "host": " ...

Optimizing font loading with angular CLI

EDIT: AFAIK This is a unique question and not related to Webpack disable hashing of image name on output because: The webpack.config file is no longer editable in the latest versions of Angular CLI. I actually want to keep the hash on the fon ...

Unable to transfer object from Angular service to controller

I am currently utilizing a service to make a $http.get request for my object and then transfer it to my controller. Although the custom service (getService) successfully retrieves the data object and saves it in the responseObj.Announcement variable when ...

Refresh Angular component upon navigation

I have set up routes for my module: const routes: Routes = [ { path: ":level1/:level2/:level3", component: CategoriesComponent }, { path: ":level1/:level2", component: CategoriesComponent}, { path: ":level1", component: ...

Best Practices for Implementing Redux Prop Types in Typescript React Components to Eliminate TypeScript Warnings

Suppose you have a React component: interface Chat { someId: string; } export const Chat = (props: Chat) => {} and someId is defined in your mapStateToProps: function mapStateToProps(state: State) { return { someId: state.someId || '' ...

Prisma: Utilizing the include option will retrieve exclusively the subobject fields

I created a function to filter the table building and optionally pass a Prisma.BuildingInclude object to return subobjects. async describeEntity(filter: Filter, include?: Prisma.BuildingInclude): Promise<CCResponse> { try { const entity = await ...

Tips for preventing the error message "The property 'map' is not present on type 'string | string[]'."

I received an error message stating Property 'map' does not exist on type 'string | string[]': const data = [ ['1', ['11']], ['2', ['21']], ['3', ['31']], ] data.map(top ...

Angular 10 - unable to bind 'formGroup' as it is not recognized as a valid property of 'form'

In my existing Angular application, I need to implement routing and a login page as the functionality expands. To integrate routing, I have included the following code: app.module.ts // Importing various modules @NgModule({ declarations: [ App ...