我收到一条关于subscribe已被弃用的错误消息。第一条消息是我的API服务,但问题出在函数getStarwarsHeroes的代码的第二部分。.subscribe被划掉,我收到了弃用的错误。
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}/`
);
}
}
我的页面,我想在那里显示星星大战人物:首先是TS文件:
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);
}
}
然后HTML文件:
<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>
1条答案
按热度按时间bvhaajcl1#
不是传入next函数和error函数,而是传入一个对象,并将next函数和error函数作为该对象的属性。
不赞成的消息是因为这是现在传入多个函数的首选方法,如果不需要其他函数,您仍然可以传入单个next函数。