Warm tip: This article is reproduced from serverfault.com, please click

TS2304: Cannot find name 'Rx'

发布于 2020-11-29 16:23:59

I came across some code in Angular that rotates between words every few seconds:

words: string[] = ['foo', 'bar', 'baz'];
word = null;

rotateWords() {
  const source = Rx.Observable.interval(1000).take(this.words.length);
  const sub = source.finally(this.rotateWords).subscribe(i => this.word = this.words[i]));  
}

Unfortunately, I get the error message "Rx is not found" in on my version of Rx (6.5.5) and Angular (10.0.9). The code seems to be written in an old-style of RxJs. How do I rewrite it in the new style?

Questioner
methuselah
Viewed
0
Owen Kelvin 2020-11-30 01:26:33

If you are using angular with rxjs 4+


import { interval } from 'rxjs'
import { take, finalize} from 'rxjs/operators'

words: string[] = ['foo', 'bar', 'baz'];
word = null;

rotateWords() {
    const source = interval(1000).pipe(take(this.words.length));
    const sub = source.pipe(finalize(this.rotateWords.bind(this))).subscribe(i => {
      this.word = this.words[i];
    });
  }
}

See Below Demo