The functionality to subscribe in ts(6385) has been marked as

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>

Answer №1

Instead of passing separate next and error functions, opt for a cleaner approach by passing an object with both functions as properties.

subscribe({
  next: (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;
    }
  },
  error: (err) => {
    console.log(err);
    loading.dismiss();
  }
})

The deprecated message indicates that using an object to pass multiple functions is now the recommended practice, but you can still use a single next function if the other functions are unnecessary.

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

How can I restrict a generic type to include the new() method?

Is there a way to create a function similar to the following in TypeScript? createEntity<TEntity>(): TEntity { return new TEntity(); } In C#, we can achieve this using: void TEntity CreateEntity<TEntity>() where TEntity : new() How would ...

Is it possible for recursive type definitions to handle generics effectively?

I have identified what I believe to be a bug in Typescript and have submitted it as an issue here. Considering that this might not get resolved quickly, I am reaching out for suggestions. Does anyone know of a better solution or workaround than the one pro ...

Unable to break down the property 'desks' of '(0 , _react.useContext)(...)' due to its undefined nature

Trying to mock DeskContext to include desks and checkIfUserPresent when calling useContext is causing an error to occur: Cannot destructure property 'desks' of '(0 , _react.useContext)(...)' as it is undefined TypeError: Cannot destruct ...

Typescript encounters a failure in typing when an object is destructured

There is a function that returns an object with two properties (res, mes) where one of them could be null: const fetchJSON = <Res, Body>(link: string, body: Body): Promise<{ res: Res; mes: null } | { res: null; mes: Popup }> => { return n ...

"Dealing with conflicts between RMQ and TypeORM in a NestJS

Every time I try to use TypeOrm, RMQ crashes. I can't figure out why. Utilizing the library golevelup/nestjs-rabbitmq has been a struggle for me. I've spent 7 hours trying to resolve this issue. @Module({ imports: [ ConfigModule.f ...

Beginner: Add "shared" module elements to app.module and include them in app.component.html as part of the app's layout

I am trying to incorporate three components from a "shared" module into app.component.html. Here is my current setup: <header></header> <div class="main-wrapper"> <div class="bg-trick"></div> &l ...

Removing Multiple Object Properties in React: A Step-by-Step Guide

Is there a way in React to remove multiple object properties with just one line of code? I am familiar with the delete command: delete obj.property, but I have multiple object properties that need to be deleted and it would be more convenient to do this i ...

The Formly form is experiencing a glitch where it does not reflect the updated default value of

My goal is to dynamically update the Formly form rendering based on changes made in the form scheme (which consists of an array of FormlyFormConfig objects). I have noticed that the updating works when adding a new object or modifying a field label, but it ...

Display only a specific range of years on the Angular Material Date picker. For example, show only the dates from 1950 to the current year, excluding any other years outside of this range

In my current project, I am utilizing the Angular Material Datepicker for selecting dates. Does anyone know how to display only a specific range of years? For example, I need to show years starting from 1950 in my Material Date Picker and remove any years ...

Confounding Typescript Type Bindings

I am facing an issue with my Typescript component that uses react-jss and the classes object for styling. The error message I'm getting is: Binding element 'classes' implicitly has an 'any' type., and I'm struggling to find a ...

Issue with Angular: Attempting to assign a value to a property that is undefined within

While utilizing a common method to call a service that executes two functions upon success and failure, I encountered an issue. Despite the call executing correctly, I faced an error when trying to assign a value from the service result to a variable withi ...

Having some issues with ng-hide in angular, it doesn't seem to be functioning properly

<nav class="menu-nav"> <ul> <li class="menu-li" ng-model="myVar"><a>Discover<i class="fa fa-chevron-down pull-right"></i></a> <div class="sub-menu" ng-hide="myVar"&g ...

Troubleshooting issues with importing modules in TypeScript when implementing Redux reducers

Struggling to incorporate Redux with TypeScript and persist state data in local storage. My current code isn't saving the state properly, and as I am still new to TypeScript, I could really use some suggestions from experienced developers. Reducers i ...

Angular 2 Google Chart: Defining column type using TypeScript

I am currently attempting to implement the Timeline chart functionality from the angular2-google-chart module for Google Charts. Unlike the other examples provided, this specific chart type requires a column type definition — a requirement not present in ...

What is the proper way to define the type when passing a function as a component prop, with or without parameters?

import { dehydrate, HydrationBoundary } from '@tanstack/react-query'; import getQueryClient from '@/lib/react-query/getQueryClient'; export async function RQBoundary<T>({ children, queryKey, fn, }: { children: React.Reac ...

I encountered an error while attempting to create an npm package from a forked repository on GitHub

Check out this GitHub repository: https://github.com/jasonhodges/ngx-gist Upon running the package command, I encounter an error: rimraf dist && tsc -p tsconfig-esm.json && rollup -c rollup.config.js dist/ngx-gist.module.js > dist/ngx- ...

Angular unable to register service worker

Looking to implement push notifications in my Angular app using vanilla JavaScript instead of the Angular service worker or @angular/pwa. In angular.json, I've specified the path to the js file under the script option. However, when the service worke ...

Utilizing prerender.io with lazy loading in Angular 2: A comprehensive guide

As Angular Universal is not expected to be included in the CLI for some time, I've had to resort to using prerender.io in order to ensure proper SEO functionality. However, my tests have shown that there are issues with lazy loaded modules causing SEO ...

Error in Typescript: The 'type' property is not found in the 'string' type

I am working on creating a React component that includes subcomponents within it. I came across this insightful article that has been guiding me through the process. The concept is to design a Modal component with distinct sections such as Modal.Header, M ...

How can we optimize promise nesting in JavaScript?

Take a look at the following code snippet: WordPress.getMediaById(res.data.featured_media) .then(function (res) { post.featuredMedia = res.data.source_url; WordPress.getUserById(post.authorId) .then(function (res) { post.authorName = res.da ...