Ionic Angular类型错误:Event无法赋值给InfiniteScrollCustomEvent
解决Ionic Angular中
Event无法赋值给InfiniteScrollCustomEvent的类型错误 问题分析
你遇到的类型错误源于Angular模板默认将ionInfinite事件的$event推断为标准Event类型,但Ionic实际触发的是自定义的InfiniteScrollCustomEvent,两者类型不匹配导致TypeScript报错。
解决方案
方法1:在组件方法中进行类型断言(推荐)
修改loadMore方法,将传入的Event断言为InfiniteScrollCustomEvent,让TypeScript识别正确的事件类型:
loadMore(event: Event) { // 将普通Event断言为Ionic的自定义无限滚动事件 const infiniteScrollEvent = event as InfiniteScrollCustomEvent; this.currentPage++; this.loadMovies(infiniteScrollEvent); }
loadMovies方法的参数类型保持InfiniteScrollCustomEvent | undefined不变,无需额外修改。
方法2:在模板中直接转换事件类型
在模板的ionInfinite绑定中,直接对$event进行类型断言:
<ion-infinite-scroll threshold="25%" [disabled]="true" position="bottom" (ionInfinite)="loadMore($event as InfiniteScrollCustomEvent)"> <ion-infinite-scroll-content loadingSpinner="bubbles" loadingText="Loading more data..."> </ion-infinite-scroll-content> </ion-infinite-scroll>
这种方式下,loadMore方法的参数类型可继续使用InfiniteScrollCustomEvent:
loadMore(event: InfiniteScrollCustomEvent) { this.currentPage++; this.loadMovies(event); }
修正后的完整代码示例
movies.page.ts
import { InfiniteScrollCustomEvent, LoadingController } from '@ionic/angular'; import { MovieService } from './../../services/movie.service'; import { Component, OnInit } from '@angular/core'; import { environment } from 'src/environments/environment'; @Component({ selector: 'app-movies', templateUrl: './movies.page.html', styleUrls: ['./movies.page.scss'], }) export class MoviesPage implements OnInit { movies: any[] = []; currentPage = 1; imageBaseUrl = environment.images; constructor( private movieService: MovieService, private loadingCtrl: LoadingController ) {} ngOnInit() { this.loadMovies(); } async loadMovies(event?: InfiniteScrollCustomEvent) { const loading = await this.loadingCtrl.create({ message: 'Loading..', spinner: 'bubbles', }); await loading.present(); this.movieService.getTopRatedMovies(this.currentPage).subscribe((res) => { loading.dismiss(); this.movies.push(...res.results); if (event) { event.target.complete(); event.target.disabled = res.total_pages === this.currentPage; } }); } loadMore(event: Event) { const infiniteScrollEvent = event as InfiniteScrollCustomEvent; this.currentPage++; this.loadMovies(infiniteScrollEvent); } }
内容的提问来源于stack exchange,提问作者Hanung Setiawan
相关产品推荐
相关产品推荐

