typescript 泛型类型Subject< T>需要1个类型参数,- Angular

lhcgjxsq  于 2022-11-30  发布在  TypeScript
关注(0)|答案(2)|浏览(176)

我正在从我的服务中获取数据,我已经意识到在订阅后取消订阅是很重要的,下面是我是如何做到的:

export class RItemComponent implements OnInit {

    apiPath = environment.apiUrl;
    private ngUnsubscribe: Subject = new Subject();

    constructor(private _sharedService: SharedService) { }

    rItems: Product[];

    ngOnInit() {
    this._sharedService.
        getReceiptItem().takeUntil(this.ngUnsubscribe).
        subscribe(products => this.rItems = products);
    }

    ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
    }
}

但现在我得到一个错误:

Generic type Subject<T> requires 1 type argument(s). subscribe

我不明白为什么?
任何形式的帮助将是真棒,谢谢!

bvk5enib

bvk5enib1#

为主题添加泛型类型

private ngUnsubscribe: Subject<any> = new Subject();
fruv7luv

fruv7luv2#

Subject类在TypeScript中有一个泛型类型参数。这意味着,该类的示例只能通过传递一个附加类型参数来创建,如下所示:

private ngUnsubscribe: Subject<MyClass> = new Subject();

相关问题