类型 'Subject<void>' 的 'this' 上下文不可分配给方法的 'this' 类型 'Observable<void>'

The 'this' context of type 'Subject<void>' is not assignable to method's 'this' of type 'Observable<void>'

我正在从 rxjs 导入 Subject,然后创建 属性 onSentenceChangeDebouncer。在我使用的构造函数中 this 所以我不确定为什么我收到错误“不可分配给方法”。看起来它与 debounceTime(300).

行有关
Error   TS2684  The 'this' context of type 'Subject<void>' is not assignable to method's 'this' of type 'Observable<void>'.
  The types returned by 'lift(...)' are incompatible between these types.
    Type 'Observable<void>' is not assignable to type 'Observable<R>'.
      Type 'void' is not assignable to type 'R'.
        'R' could be instantiated with an arbitrary type which could be unrelated to 'void'.
import { Subject } from "rxjs";

onSentenceChangeDebouncer: Subject<void> = new Subject<void>();

constructor(
  this.onSentenceChangeDebouncer
    .debounceTime(300)
    .subscribe(() => {
      this.updateConceptDependencies();
      this.compileSentence();
    });
}

StackBlitz

您将代码放在错误的范围内,您可能想这样做:

 constructor() {
 this.onSentenceChangeDebouncer
            .debounceTime(300)
            .subscribe(() => {
                this.updateConceptDependencies();
                this.compileSentence();
            });
}
    

您的构造函数似乎缺少此结束符 ')' 您的代码应如下所示:

import { Subject } from "rxjs";


class SomeClass {
    onSentenceChangeDebouncer: Subject<void> = new Subject<void>();
    
    constructor() {
        this.onSentenceChangeDebouncer
            .debounceTime(300)
            .subscribe(() => {
            
            
               this.updateConceptDependencies();
               this.compileSentence();
            });

    }

    updateConceptDependencies() { /* some logic */ }
    compileSentence() { /* some logic */ }

}

我认为问题在于您订阅了 Subject<T> 而不是 Observable<T>。更正后的代码应该是:

onSentenceChange$: Observable<void> = this.onSentenceChangeDebouncer.asObservable();

this.onSentenceChange$.debounceTime(300).subscribe(() => { ... });

一样,错误的发生是由于 Subject<T>.lift 签名在 v5.4.2 之前的包中被破坏,因此也可以通过更新 Subject<T>.lift 来消除它=14=]到那个版本。

编辑 这适用于 rxjs +6.0

你忘记说主题了!试试这个:

import { Subject } from "rxjs";

onSentenceChangeDebouncer: Subject<void> = new Subject<void>();

onSentenceChangeDebouncer$ = this.onSentenceChangeDebouncer.pipe(
            .debounceTime(300)
            )
            .subscribe(() => {
                this.updateConceptDependencies();
                this.compileSentence();
            });

 constructor(){}
        

我建议你不要在构造函数中订阅,而是更喜欢 onInit Hook,或者像例子一样,直接在组件的竞争中。

通过这种方式,您将获得所需的反应能力