I am encountering an error message regarding the deprecation of the subscribe function in my code. The issue seems to be with the second part of the code for the getStarwarsHeroes function, where the .subscribe method is being deprecated.
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import { Observable} from 'rxjs';
export interface ApiResult {
page: number;
results: any[];
total_pages: number;
total_results: number;
}
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) {}
getStarwarsHeroes(page:number =1): Observable<ApiResult> {
return this.http.get<ApiResult>(`https://swapi.dev/api/people/${page}/`);
}
getStarwarsDetails(id:string): Observable<any>{
return this.http.get<ApiResult>(
`https://swapi.dev/api/people/${id}/`
);
}
}
Here is the TypeScript file for displaying the Star Wars characters on my page:
import { Component, OnInit } from '@angular/core';
import { ApiService} from '../api.service';
import { InfiniteScrollCustomEvent, LoadingController} from '@ionic/angular';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
starwars:any=[];
currentPage:number= 1;
constructor(
private apiService:ApiService,
private loadingCtrl: LoadingController
) {}
ngOnInit() {
this.loadStarwars();
}
async loadStarwars(event?: InfiniteScrollCustomEvent) {
const loading= await this.loadingCtrl.create({
message: 'Loading..',
spinner: 'bubbles',
});
await loading.present();
this.apiService.getStarwarsHeroes(this.currentPage).subscribe(
(res) => {
loading.dismiss();
this.starwars.push(...res.results);
console.log(this.starwars);
event?.target.complete();
if (event) {
event.target.disabled = res.total_pages === this.currentPage;
}
},
(err) => {
console.log(err);
loading.dismiss();
}
);
}
loadMore(event: InfiniteScrollCustomEvent) {
this.currentPage++;
this.loadStarwars(event);
}
}
And finally, here is the HTML file:
<ion-header [translucent]="true">
<ion-toolbar>
<ion-title>
StarWars Characters
</ion-title>
<ion-button slot="start">
<ion-menu-button menu="main-menu"></ion-menu-button>
</ion-button>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-card
*ngFor='let item of starwars'
[routerLink]="[item.id]"
>
<ion-card-header>
<ion-card-title slot="start">{{item.name}}</ion-card-title>
</ion-card-header>
<ion-card-content slot="end">{{item.gender}} </ion-card-content>
</ion-card>
</ion-content>