通用类型Subject <T>需要1个类型参数。-角度

Rox*_*Pro 5 rxjs typescript angular-services angular

我正在从服务中获取数据,我对订阅后取消订阅很重要,这是我的做法:

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

但是现在我得到一个错误:

泛型类型Subject需要1个类型参数。订阅

我不明白为什么?

任何帮助都会很棒,谢谢!

Sac*_*aka 10

为主题添加通用类型

private ngUnsubscribe: Subject<any> = new Subject();
Run Code Online (Sandbox Code Playgroud)

  • 不鼓励`any`。几乎总是有更准确的类型。如果您真的不知道或无法知道类型是什么,请考虑使用新类型 `unknown`。https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html#new-unknown-top-type (3认同)

ggr*_*nig 8

Subject班有一个打字稿泛型类型参数。这意味着只能通过传递其他类型参数来创建此类的实例,如下所示:

private ngUnsubscribe: Subject<MyClass> = new Subject();
Run Code Online (Sandbox Code Playgroud)