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

Bring in typings from a package with an alternate title

I have a project that I am currently converting to typescript. In this project, I am using the package ng-idle. Additionally, there is a corresponding @types package named angular-idle, which contains the file @types/angular-idle/index.d.ts with the follow ...

Eliminating empty elements from arrays that are nested inside other arrays

I am facing a challenge with the array structure below: const obj = [ { "description": "PCS ", "children": [ null, { "name": "Son", ...

How can I prevent the installation of my Ionic 2 application on devices that have been rooted or jailbroken?

I am currently working on a project involving an Ionic 2 and Angular 2 application. I need to implement a feature that checks whether the device is rooted (in the case of Android) or jailbroken (in the case of iOS). I have experimented with various packag ...

Utilizing Angular signals to facilitate data sharing among child components

I have a main component X with two sub-components Y and Z. I am experimenting with signals in Angular 17. My query is how can I pass the value of a signal from sub-component Y to sub-component Z? I have attempted the following approach which works initial ...

The latest version of IntelliJ Idea Ultimate, 2023.2.5, does not offer compatibility with the updated control flow features in Angular

I recently made the switch to Angular 17 in my project and noticed that Idea is not recognizing the new syntax in HTML templates. <mat-menu #menu="matMenu"> @for (menuItem of getData().menu.items; track menuItem) { & ...

Error TS2322: This type cannot be assigned to type 'never' in Angular

Trying to incorporate the websocket (sockjs and stomp) into my Angular project for a chat messaging feature, I encountered an issue in my service.ts file. Specifically, when I defined the addMessage method like so: public messages = []; addMessage(messa ...

"Acquiring the version number in Angular 5: A step-by-step

How can I retrieve the version from my package.json file in Angular 5 project? I am using Angular-Cli: 1.6.7 and npm 5.6.0 Here is a snippet from my enviroment.ts file: export const enviroment = { VERSION: require('../package.json').versio ...

Error message 'Chart was not disposed' is displayed in amChart while rendering live data through a socket connection

I encountered a similar issue with the amChart displaying a "chart was not disposed" warning, leading to memory leakage. To find a solution, I referred to the following guide: However, since I am updating the chart in real-time using socket connections a ...

Displaying properties of a class in Typescript using a default getter: Simplified guide

Here is an interface and a class that I am working with: export interface ISample { propA: string; propB: string; } export class Sample { private props = {} as ISample; public get propA(): string { return this.props.propA; } public se ...

Caution: The file path in node_modules/ngx-translate-multi-http-loader/dist/multi-http-loader.js relies on the 'deepmerge' dependency

My micro-frontend angular project is using mfe (module federation). I recently updated it from angular 13 to 14 and encountered some warnings such as: node_modules\ngx-translate-multi-http-loader\dist\multi-http-loader.js depends on ' ...

Nested MD-list-item in Angular 2 Material

Trying to implement nested lists in a sidenav using Angular 2 with material design. Here is the initial code: <md-sidenav #sidenav class="sidenav" mode="over" opened> <md-nav-list> <md-card class="user-card"> ...

Generate detailed documentation for the functional tests conducted by Intern 4 with automated tools

I need to automatically generate documentation for my Intern 4 functional tests. I attempted using typedoc, which worked well when parsing my object page functions. However, it failed when working with functional test suites like the one below: /** * Thi ...

Attempting to retrieve JSON data from an API while currently working from local server

I need to retrieve JSON data from , but I keep encountering the error message: "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access." Here is the code I ...

Automatically select the unique item from the list with Angular Material AutoComplete

Our list of document numbers is completely unique, with no duplicates included. I am attempting to implement a feature in Angular Material that automatically selects the unique entry when it is copied and pasted. https://i.stack.imgur.com/70thi.png Curr ...

Ways to retrieve a Class Level Variable within the onCellValueChanged function in agGrid

Exploring Angular with Typescript for the first time. I'm trying to access Class Level Variables within the onCellValueChanged event of agGrid, but encountering the following error: Cannot read property 'updateDict' of undefined Here&apo ...

When using Angular 2, the array.splice() function is causing the elements to be removed from the

I am currently working with an HTML table that has default checked rows. <table> <tr> <th></th> <th>Id</th> <th>Name</th> <th>Initial</th> </tr> ...

Upon successfully logging into the app, Azure AD B2C integrated with MSAL and Angular will automatically redirect users to the login page

I recently updated my Angular app to make it accessible to customers by switching from ADAL to MSAL for authentication. I configured the app with Azure AD B2C credentials and everything seems to be working smoothly, except for one issue. When I try to logi ...

typescript is reporting that the variable has not been defined

interface User { id: number; name?: string; nickname?: string; } interface Info { id: number; city?: string; } type SuperUser = User & Info; let su: SuperUser; su.id = 1; console.log(su); I experimented with intersection types ...

Encountering a NullInjectorError while running unit tests in Angular 14 specifically related to a missing provider for Untyped

After transitioning my project from Angular 13 to Angular 14, I encountered this error message: Error: NullInjectorError: R3InjectorError(DynamicTestModule)[UntypedFormBuilder -> UntypedFormBuilder]: NullInjectorError: No provider for UntypedFor ...

What is the process for extracting the "path expression" from an interface in TypeScript?

My goal is to achieve the following structure: type Post = { id: number title: string author: { name: string } comments: { text: string }[] } type ExtractPathExpressions<T> = ??? type Paths = ExtractPathExpressions<Post> / ...