Strategies for increasing the number of images in Angular

At the start, 15 images are displayed from the API. However, the "Get dogs" button should load an additional 15 images each time it's clicked, but currently, it doesn't work. How can we fix this issue?

http.service.ts - a service that interacts with the API using HttpClient

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { DogInfo } from '../interface/dogInfo';

@Injectable({
  providedIn: 'root',
})
export class HttpService {

  httpHeaders = new HttpHeaders({
    Authorization: 'YOUR_KEY_HERE',
  });

  DOGS_FETCHED = 0;
  DOGS_TO_FETCH = 15;

  constructor(private http: HttpClient) {}

  fetchDogsFromApi(): Observable<DogInfo[]> {
    const page = (this.DOGS_FETCHED + this.DOGS_TO_FETCH) / this.DOGS_TO_FETCH - 1;

    const url = `https://api.thedogapi.com/v1/breeds?page=${page}&order=desc&limit=${this.DOGS_TO_FETCH}`;

    return this.http.get<DogInfo[]>(url, { headers: this.httpHeaders })
      .pipe((response) => {
        this.DOGS_FETCHED += this.DOGS_TO_FETCH;
        return response;
      });
  }
}

dogsList.component.ts - handling image fetching and getDogs functionality

import { AfterViewInit, Component } from '@angular/core';
import { HttpService } from 'src/app/service/http.service';

@Component({
  selector: 'app-dogsList',
  templateUrl: './dogsList.component.html',
  styleUrls: ['./dogsList.component.css']
})
export class DogsListComponent implements AfterViewInit {

  constructor(private httpService: HttpService) {}

  doggos: any = [];
  
  onFetchDogsFromApi(): any {
    this.httpService.fetchDogsFromApi().subscribe(
      (response) => this.doggos = response
    );
  }

  getDogs() {
    this.onFetchDogsFromApi();
  }

  ngAfterViewInit(): void {
    this.onFetchDogsFromApi();
  }
}

dogsList.component.html - displaying a list of images using ngFor directive

<div class="container">
    <div id="dogs">
        <div *ngFor="let item of doggos" >
            <p style="display: none;">{{item.id}}</p>
            <img src={{item.image.url}} ngClass="zoom-img" routerLink="/home/{{item.id}}" />
        </div>
    </div>

    <button class="btn" (click)="getDogs()">Get dogs</button>
</div>

Answer №1

Seems like you're always replacing the current set of 15 images with the next 15.

Instead of replacing them, consider simply adding the next 15 images to the existing array. So, instead of doing this:

this.httpService.fetchDogsFromApi().subscribe(
  (response) => this.doggos = response
);

Try this approach instead:

this.httpService.fetchDogsFromApi().subscribe(
  (response) => this.doggos.push(...response)
);

Answer №2

Why do you always inquire about the same link repeatedly?

Try this approach instead:

fetchCatsFromApi(page:number,limit:number): Observable<CatInfo[]> {
   const url = `https://api.thecatapi.com/v1/breeds?page=${page}&order=desc&limit=${limit}`;
..
}

Make sure to use the following method when calling your service:

this.page++;
this.onFetchCatsFromApi(this.page,10);

Remember: It's advisable to "manage" the page from the component rather than the service itself.

Answer №3

Make sure to add the latest data to the doggos array by following the code snippet provided.

this.httpService.fetchDogsFromApi().subscribe(
  (newData) => this.doggos = [...this.doggos, ...newData];
);

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

Typescript challenge: Implementing a route render attribute in React with TypeScript

My component has props named project which are passed through a Link to a Route. Here's how it looks (the project object goes in the state extended property): <Link to={{ pathname: path, state: { project, }, }} key={project. ...

How can TypeScript associate enums with union types and determine the type of the returned object property?

I have a unique enum in conjunction with its corresponding union type. type User = { name: string, age: number } export enum StorageTypeNames { User = "user", Users = "referenceInfo", IsVisibleSearchPanel = "searchPane ...

Error: Failed to locate package "package-name" in the "npm" registry during yarn installation

While working on a large project with numerous sub-projects, I attempted to install two new packages. However, YARN was unable to locate the packages despite the .npmrc being present in the main directory. ...

How can you check the status of a user in a Guild using Discord JS?

Is there a way to retrieve the online status of any user in a guild where the bot is present? Although I can currently access the online status of the message author, I would like to be able to retrieve the online status of any user by using the following ...

"Exploring the dynamic duo: Algolia integration with Angular

I've been following a tutorial on implementing instantsearchjs in my website, which can be found here. Everything is set up correctly and I can query for results in .JSON format from my website. However, I'm having trouble figuring out how to r ...

Safe way to implement map and spread operator in your codebase

Is there a workaround for this issue? I am working with an interface, IFoo, and an array of data IFoo[]. My goal is to map this data and modify a single property. It should look something like this const mapper = (foos: IFoo[]): IFoo[] => { return foo ...

Prevent ESLint from linting files with non-standard extensions

My .estintrc.yaml: parser: "@typescript-eslint/parser" parserOptions: sourceType: module project: tsconfig.json tsconfigRootDir: ./ env: es6: true browser: true node: true mocha: true plugins: - "@typescript-eslint" D ...

Eliminate JSON data that pertains to dates that are either in the past or future

I am working on integrating upcoming classes and past classes components into my application. I have successfully stored the schedule of classes and can retrieve them using backend services. However, I need to display only the upcoming classes in one compo ...

Is MongoDB still displaying results when the filter is set to false?

I am currently trying to retrieve data using specific filters. The condition is that if the timestamp falls between 08:00:00 and 16:00:00 for a particular date, it should return results. The filter for $gte than 16:00:00 is working correctly, but the $lte ...

What is the syntax for defining parameters in an overloaded arrow function in TypeScript?

Trying to create an async arrow function that can handle a single image object or an array of image objects. I'm new to TypeScript overloading and may be approaching this the wrong way. Here's what I've come up with: type ImageType = { ...

A guide on incorporating ng2-canvas-whiteboard into your Ionic 3 project

I'm trying to implement the npm package ng2-canvas-whiteboard into my Ionic 3 app. I followed all the instructions on the npm page and here is my package.json: "dependencies": { "@angular/common": "4.0.2", "@angular/compiler": "4.0.2", ...

What is the purpose of using both forRoot() and forChild() in the RouterModule

What is the purpose of Angular RouterModule using forRoot() and forChild() methods? I recently learned about the forRoot pattern and how it protects provider singletons from being imported multiple times (https://angular.io/guide/singleton-services#the-fo ...

Creating a library that relies on Cypress without the need to actually install Cypress

We have adopted the page object pattern in our testing and recently made the decision to move them into a separate npm-published library for reusability. Considering the heavy nature of Cypress and potential version conflicts, we believe it's best no ...

Unable to generate or compose a text document within my Ionic application

After attempting to create a file and write in it, I'm encountering an issue where the file appears to be created but is not visible when navigating to the folder. Can someone please point out what might be going wrong? Below is my code snippet: th ...

Guide on linking an object retrieved from an API to an input text field in Angular

I have been working on reading API responses in Angular and displaying them in input text fields. While I am able to successfully call the API and view the response in the console, I am facing challenges when it comes to capturing the response in an object ...

The continuity of service value across parent and child components is not guaranteed

My goal is to update a value in a service from one component and retrieve it in another. The structure of my components is as follows: parent => child => grandchild When I modify the service value in the first child component, the parent receives t ...

Encountering an issue with Angular 8 and Material where a table does not fully render on mobile browsers like Chrome, causing rows to only half

Currently, I have an Angular 8 application integrated with Material v8.2.3 where a table with expanding rows is being used. While everything functions perfectly on desktop browsers, there seems to be an issue when accessing the application on mobile phone ...

Issue with Primeng table: row grouping width does not work properly when scrollable is enabled

Currently, I am implementing a Primeng table within an Angular project. Below is the code snippet showcasing how the table is being utilized: <p-table [value]="cars" dataKey="brand" [scrollable]="'true'" scrollHeight="400px"> <ng-te ...

What steps can be taken to ensure that the requestAnimationFrame function does not redraw the canvas multiple times after a button click?

I am currently working on a project where I am drawing a sin wave on a canvas and adding movement to it. export class CanvasComponent implements OnInit { @ViewChild('canvas', { static: true }) canvas: ElementRef<HTMLCanvasElement>; ...

Navigational menu routing with AngularJS2 using router link paths

Currently, I am working on developing a navigation menu using angularJS2. Here is the snippet from my app.component.ts: import {provide, Component} from 'angular2/core'; import {APP_BASE_HREF, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, HashLocati ...