Learn how to retrieve images from the web API at 'https://jsonplaceholder.typicode.com/photos' and showcase them on a webpage using Angular10

  1. Using the API "https://jsonplaceholder.typicode.com/photos", I have access to 5 properties:

    albumId: 1
        id: 1
    thumbnailUrl: "https://via.placeholder.com/150/92c952"
     title: "accusamus beatae ad facilis cum similique qui sunt"
       url: "https://via.placeholder.com/600/92c952"
    
  2. This API provides URLs for both Images and Thumbnails.

  3. In one.component, I aim to display Albums with their Album Id on the First Page.

  4. Upon clicking on a specific album, the Thumbnails of the Images (two.component) should be visible.

  5. Furthermore, clicking on a thumbnail will open the Image in a pop-up gallery.

Sample Code Below

one.component.html

<div class="container">

 <h5>Albums with corresponding AlbumIds will be displayed here in separate blocks.</h5>
 
 <!-- Display albums serially based on their albumId -->
 <h3 *ngFor=" " (click)="thumbnailOnClick()" routerLink="/two">albumID</h3> 

</div> 

one.component.ts

    export class OneComponent implements OnInit {
      
     constructor(private helperService:HelpService) { };
    
      ngOnInit(){
     
       this.getAlbumData();  
    
      };
      
      apiAlbumData=[];//data from api is stored in it.
    
      getAlbumData(){
    
        this.helperService.getAlbums().subscribe(apiAlbumData=>{
    
          console.log(apiAlbumData);
    
          //looping through apiAlbumData in console
          for(let value of this.apiAlbumData){
    
            console.log(value);        
    
          }
        })
      }
    }

helper.service

    export class HelpService {
    
      constructor(private http:HttpClient) { }
    
      getAlbums():Observable<any>{
       
        const url = 'https://jsonplaceholder.typicode.com/photos';
       
         return this.http.get(url);
       
        };
    };

Answer №1

When working with Angular, it is important to utilize http.get to fetch data from an API. One approach is to create an empty array and then update it once the data has been retrieved. I opted to use rxjs map in this scenario for mapping purposes. Additionally, creating an interface can help ensure cleaner code structure, especially when dealing with specific object properties/fields - such as the 5 properties mentioned. Within your HTML template, you can iterate through the array data and initially display the ID in your one.component file. Below is a snippet of my implementation:

// Defining the interface
interface IPhoto {
   albumId: number;
   id: number;
   title: string;
   url: string;
   thumbnailUrl: string;
}

// Array property within the class for referencing API data
public postArray: IPhoto[];

// Function to fetch API photos
fetchApiPhotos() {
    const apiUrl = 'https://jsonplaceholder.typicode.com/photos';
    return this.http.get(apiUrl).pipe(
        map((responseData: IPhoto[]) => {
            // Assigning received data to the array
            return this.postArray = responseData;
        })
    );
}

// HTML Template section
// Displaying IDs by looping through the array data
// Implement a function to emit data upon button click,
// for consumption by component two.
<article>
   <div *ngFor="let photo of postArray">
       <h2>{{photo.id}}</h2>
       <button (click)="showPhotoDetails(photo)">Details</button>
   </div>
</article>

// Event handling function for button click
// Dispatches emitted data, which can be received by the second component.
showPhotoDetails(photo: IPhoto) {
    this.photoItemClicked.emit(photo);
}

Consider utilizing Angular emit or services with observables if there's a need for other components to listen/subscribe to updates.

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

Removing an element with a specific class that was created with Javascript can be done by clicking outside the box

I needed to eliminate an element that was created using JavaScript of a specific class when clicked outside the box. I have created a color-picker using .createElement and added a class to it. Now, my goal is to remove that picker whenever a click occu ...

Error is being thrown due to defining a variable after it has already been declared and

Before I use a variable, I encountered the issue of using it before its definition, interface IProps extends WithStyles<typeof STYLES>; const STYLES = () => ({ }) Although it didn't cause any errors, a warning appeared: STYLES used befo ...

What methods are available for modifying nodes generated dynamically?

I have been on a quest for quite some time now to find a way to manipulate HTML content that has been dynamically added. Initially, I fetch a cross-domain website using getJSON: $.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent ...

Leveraging ASCII characters within the .htaccess file

I'm currently working on developing my own local network website and I'm interested in adding password protection to certain parts using .htaccess. However, the guide I've been following mentioned that they need to be saved with ASCII encodi ...

Preventing scrolling in one div while focusing on another div

I am currently in the process of creating a website that functions as a single page site. The main feature of the site is a masonry grid of images. When a user clicks on an item, a detailed panel slides in from the left. Once the panel is closed, it slide ...

`Managing select tag data in Angular reactive forms`

Having an issue with selecting the gender option from JSON formatted data received from the backend. The gender is displayed as a select tag on the frontend, but it does not pre-select the option that corresponds to the gender value in the JSON data. The b ...

Ways to apply the strategy pattern in Vue component implementation

Here's the scenario: I possess a Cat, Dog, and Horse, all of which abide by the Animal interface. Compact components exist for each one - DogComponent, CatComponent, and HorseComponent. Query: How can I develop an AnimalComponent that is capable of ...

Issue with CSS Transform Causing Rendering Errors in Both Chrome and Firefox

While a pixel here or there can be overlooked, in this case, precision is essential for the perfect rendering of this simple menu. The spacing between menu items must be impeccably equal to avoid any merging or disjointed appearance. Currently, the sep ...

Tips on Incorporating CSS in import.io Connect Extract

By utilizing the import.io connector, I successfully extracted a portion of HTML from the source website. The output was returned as "html" type, consisting of a single table of data with styles defined in the body HTML but not fully extracted. Consequentl ...

having difficulty adjusting the background color of a div that is positioned absolutely

Hey there! I am new to the world of html/css and working on my very first webpage. I'm facing an issue with setting the background color for a div with the class inner. Currently, it is displaying the background color set in the banner-bottom class. ...

How can I convert a number to the format of hh:mm using Angular?

Within my form, there is an input field that should only accept numbers. Is it possible to format the input number into a hh:mm format once the user enters it? I prefer not to use input type = time. Do you have any suggestions for achieving this? ...

Guide to opening all href links in a new window

When loading HTML content parsed from an email to a frame, the issue arises when there is an href link that tries to open in the same frame. I want to modify it so that it opens in a new tab instead. Usually, setting the target to _blank in the href would ...

When attempting to compile my Angular project using the command ng build --prod, I encountered a server error stating that the document

Everything was running smoothly when I was working on my local machine, but once I uploaded the files generated from ng build --prod to the server, a problem arose. Now, whenever I try to route via a button in my components, an error appears. When I clic ...

"Exploring the Possibilities of Dynamic Styling with VueJS

I am facing an issue with a data property called editMode set on a Vueity Card. When I click on a button, the editMode switches to true and an icon appears on the v-img. However, I want to adjust the opacity of the image to 0.3 when editMode is true, witho ...

Generating unique identifiers for ng-model in AngularJS

Issue - ng-model is not generating dynamically. I have dynamic input boxes and I am attempting to create ng-model dynamically like test[1], test[2], etc. However, when inspecting the form with Firebug, all input elements only show - test[shiftnumber]. HT ...

Tips for correctly cloning a table row:

Currently, I am engaged with a Django project that involves incorporating a form within a table structure. <table name="mytable" id="table_purchase" role="grid"> <thead> <tr> <th class="text-center" hidden>No</th& ...

Using Javascript's Speech Recognition to activate a button

I am new to using JavaScript Speech Recognition and decided to work with the Annyang library. My goal is to automatically trigger the "show date" button when the user says 'hello', without actually clicking the button. However, I've been fac ...

Organizing data with JavaScript: Transforming a flat array into nested JSON structures

In my front-end TypeScript file, there is a list called poMonths: 0: {id: 1, companyName: "company14", companyId: 14, flActive: true, purchaseMonth: "2019-12-15T00:00:00", purchaseMonthString: "Dec-2019" , year: 2019, month: "December"} 1: {id: 2, company ...

Turn off browser image caching

In order to provide users with fresh weather updates, my Earth weather web application receives new weather maps every six hours as images. I want to prevent the browser from caching these images to ensure that the user always sees the most current data, r ...

What could be the reason for the Angular dropdown values not appearing?

Encountering an issue with binding data to a dropdown element, as the dropdown displays NOTHING SELECTED. <select #classProductTypeCombobox name="classProductTypeCombobox" class="form-control col-md-3" [(ngModel)]="classifica ...