Angular项目TS文件报Subscription缺失属性错误如何解决

报错原因
该错误是rxjs版本冲突导致:你项目中安装的rxjs版本与@scullyio/ng-lib依赖的rxjs版本不一致,两个不同版本导出的Subscription类型定义不匹配,因此出现属性缺失的报错。
解决方法
- 删除项目根目录下的
node_modules文件夹,以及包管理器锁文件(package-lock.json/yarn.lock/pnpm-lock.yaml) - 确认
package.json中rxjs版本为7.4.0~7.8.1的稳定7.x版本,不要使用rxjs 8预览版或6.x以下的旧版本 - 重新执行依赖安装命令:
- npm用户执行:
npm install - yarn用户执行:
yarn install - pnpm用户执行:
pnpm install
- npm用户执行:
可选优化方案
如果不想调整依赖版本,也可以使用Angular内置的自动销毁订阅能力,无需手动声明和管理Subscription实例,修改后的代码如下:
import { Component, OnInit, DestroyRef } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { ScullyRoute, ScullyRoutesService } from '@scullyio/ng-lib'; @Component({ selector: 'app-articles', templateUrl: './articles.component.html', styleUrls: ['./articles.component.scss'] }) export class ArticlesComponent implements OnInit { posts: ScullyRoute[] = []; constructor( private scullyService: ScullyRoutesService, private destroyRef: DestroyRef ) { } ngOnInit(): void { this.scullyService.available$ .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe(posts => { this.posts = posts.filter(post => post.title); }); } }
该方案适配Angular 14及以上版本,无需手动实现OnDestroy钩子调用unsubscribe,会在组件销毁时自动取消订阅。
内容的提问来源于stack exchange,提问作者user2024080
相关产品推荐
相关产品推荐

