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>