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

Angular module not found: Solving the "Cannot find module" issue

Currently, I am in the process of developing an angular 7 application and I have limited knowledge about it. Could someone please assist me in understanding why it is unable to locate the component.ts files? These files do exist in the paths mentioned by t ...

What is the best method for sending form data requests using HttpClient?

Currently, I am faced with the task of uploading a file to our server. In the past, I have successfully accomplished this using the Http module from the @angular/http library. However, in order to better integrate with our current project, we have decided ...

What is the reason behind the `h-full`/`height:100%` not completely filling the void within a div element?

The issue lies in the structure of my content, which includes a title, a subtitle, and a footer. My desire is for the subtitle's div to fill the gap between the title and the footer. I attempted using h-full on the div element, but it had no noticeab ...

The head tag specification doesn't properly include the CSS file reference

I have a question regarding my HTML5 web page and the way I am referencing a CSS file in the head tag. Currently, I have it set up like this: <head> <link rel="stylesheet" href="css/style.css" type="text/css"/> </head> However, it d ...

Using React Native's stylesheet to apply multiple values in a CSS statement

Here's a scenario to help clarify my question: Imagine I want to add margin to an element in the following way: const myView = () => <View style={styles.viewStyle}></View> const styles = StyleSheet.create({ viewStyle: { margin: ...

Is it possible to create a Cypress report that only includes the successful test cases and excludes the failed ones?

Hello everyone, I trust you are well. Currently, I am seeking a solution to exclude failed test cases from Cypress XML report when using Junit as a reporter. The issue arises when importing test results into Jira, as failures create duplicate tests instead ...

How to toggle code block visibility in Angular's ngOnInit() method

I'm currently analyzing different design patterns to optimize the number of REST calls when implementing a 'save while typing feature'. To provide a general overview, in my ngOnInit() function, I have included the following code snippet (wit ...

Is it possible to utilize the returned value of a function within an if statement?

Is there a way to return the result of a function without needing to declare a variable? Can you return the result of a function in a single line? How can you return the result of a function inside an if statement? Is it possible to use a function's ...

The Bootstrap navigation bar is experiencing issues and is not functioning properly, as the classes are not

<nav class="navbar navbar-default"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" d ...

Sort information based on the initial letter

My challenge is to accurately filter data by the starting letter only, not including middle letters. For example, if I have the word "Karnataka" and want to filter by the letter "K", searching with middle letters like "rna" still filters the result. Howe ...

Extracting data from websites: How to gather information from dynamic HTML elements

On the website I am exploring, there is a dynamic graph with descriptions below it that keep changing. My goal is to extract all these trajectory descriptions. The HTML code snippet related to the description area looks like this: <div class="trajDesc ...

Attempting to revert the imported module back to its initial/default mock configuration

When working on my test file, I utilize a folder named mocks which contains various exported functions. Most of the time, I rely on the mocks folder to perform all necessary tasks. However, there is one scenario where I need to adjust the return value to a ...

Directly mapping packages to Typescript source code in the package.json files of a monorepo

How can I properly configure the package.json file in an npm monorepo to ensure that locally referenced packages resolve directly to their .ts files for IDE and build tooling compatibility (such as vscode, tsx, ts-node, vite, jest, tsc, etc.)? I want to a ...

Discovering the absolute path to @font-face fonts using Firebug

Is it possible to retrieve the absolute URL of a web font specified within an @font-face rule using tools like Firebug? For example: When inspecting the main.css file for a website in Firebug, you may come across this code snippet: @font-face { font ...

What are some ways to make source code more visually appealing on an HTML/JSP page as it is being

I've recently created a webpage with some Java source code, neatly organized within blocks. However, I'm looking to enhance its appearance so it truly looks like Java code. Take a look at my page's code here for reference: Are there any onl ...

Integrating d3.js into an Angular 2 project

Trying to incorporate the d3.js library into a MEAN application using angular2. Here are the steps I've taken: npm install d3 tsd install d3 In mypage.ts file (where I intend to show the d3.js graph) // <reference path="../../../typings/d3/d3.d ...

Adjust the width of the table's td elements

I am looking to create a table similar to the one shown above. Here is my implementation. Please review my JSFiddle. HTML: <table border="0" id="cssTable"> <tr> <td>eredgb</td> <td><a href="self">0 ...

What is the best way to modify the KeyName in an object?

Having difficulty parsing an Object by changing keynames due to the error message "Element implicitly has an 'any' type because expression of type 'keyof SignInStore' can't be used to index type '{}'". interface SignInSto ...

Building a Div Tag Layout with CSS for Full Width and Left Position of 300px

Experiencing some trouble with styling a div element. My goal is to have the div start at left:300px and stretch across the entire width of the browser window. However, when I apply width:100%, the div extends beyond the boundaries of the browser screen. ...

Ensure that any changes to the FormControl are detected and trigger an Observable change without requiring user interaction, using .distinctUntilChanged

In my application, I have implemented a FormControl/service that updates when the user types input into a field. Here's how it works: term = new FormControl(); page = new BehaviorSubject(1); .. .. // Calling the search function search(th ...