В этом случае вы можете иметь свою переменную Observable - у вас есть цепочка операторов RxJS
, и в вашем коде вы хотите подписаться на поток цепочки много раз. Поэтому, чтобы не объединять эти операторы каждый раз, вы можете удерживать их в свойстве и добавлять к нему только один .susbcribe
.
this.heroes$ = this.searchTerms.pipe(
// wait 300ms after each keystroke before considering the term
debounceTime(300),
// ignore new term if same as previous term
distinctUntilChanged(),
// switch to new search observable each time the term changes
switchMap((term: string) => this.heroService.searchHeroes(term)),
);
inOneMethod() {
this.heroes$.subscribe(data => this.first = data);
}
inAnotherMethod() {
this.heroes.subscribe(data => this.second = data);
}