Angular 帮助我们在某些变量发生变化时开始发射的 Rxjs 运算符
Angular Rxjs operator that help us start emitting when some variable changes
我只想知道是否有一些 rxjs 运算符可以延迟我的 observable 在我的变量设置为 true 时开始发射。
Angular 上的类似内容:
loading: boolean;
constructor () {
this.subscriptions.push(
this._messageService.loadMyEvent$.pipe(
// here the operator that emitts data when loading is set to true
).subscribe(response => {
// load data
this.loadData();
this.loading = false;
})
);
}
ngAfterViewInit(): void {
this.loading = true;
}
因此,对于所有这些,我想在加载设置为 true 时调用 loadData(),这意味着我的所有内容都已呈现 (AfterViewInit)。谢谢。
您可以使用像 ReplaySubject
这样的多播可观察对象而不是布尔原语来发出值。然后可以使用 RxJS combineLatest
函数将其与可观察源结合起来。它会在它的任何源发出时发出。但请注意,所有来源必须至少发射一次,combineLatest
才能开始发射。您也可以使用 filter
运算符仅在 loading
为真时才前进。
尝试以下方法
控制器
loading: ReplaySubject<boolean> = new ReplaySubject<boolean>(1);
constructor () {
this.subscriptions.push(
combineLatest(
this._messageService.loadMyEvent$,
this.loading
).pipe(
filter(([response, loading]) => loading) // <-- emit only when `loading` is true
).subscribe({
next: ([response, loading]) => {
// load data
this.loadData();
this.loading = false;
},
error: error => {
// handle error
}
})
);
}
ngAfterViewInit(): void {
this.loading.next(true); // <-- push `true`
}
这真的取决于你到底想做什么,但你可以合并 EMPTY
:
import { EMPTY } from 'rxjs';
...
this._messageService.loadMyEvent$.pipe(
switchMap(loading => loading ? someObservable : EMPTY),
).subscribe(response => {
// load data
this.loadData();
this.loading = false;
});
我只想知道是否有一些 rxjs 运算符可以延迟我的 observable 在我的变量设置为 true 时开始发射。
Angular 上的类似内容:
loading: boolean;
constructor () {
this.subscriptions.push(
this._messageService.loadMyEvent$.pipe(
// here the operator that emitts data when loading is set to true
).subscribe(response => {
// load data
this.loadData();
this.loading = false;
})
);
}
ngAfterViewInit(): void {
this.loading = true;
}
因此,对于所有这些,我想在加载设置为 true 时调用 loadData(),这意味着我的所有内容都已呈现 (AfterViewInit)。谢谢。
您可以使用像 ReplaySubject
这样的多播可观察对象而不是布尔原语来发出值。然后可以使用 RxJS combineLatest
函数将其与可观察源结合起来。它会在它的任何源发出时发出。但请注意,所有来源必须至少发射一次,combineLatest
才能开始发射。您也可以使用 filter
运算符仅在 loading
为真时才前进。
尝试以下方法
控制器
loading: ReplaySubject<boolean> = new ReplaySubject<boolean>(1);
constructor () {
this.subscriptions.push(
combineLatest(
this._messageService.loadMyEvent$,
this.loading
).pipe(
filter(([response, loading]) => loading) // <-- emit only when `loading` is true
).subscribe({
next: ([response, loading]) => {
// load data
this.loadData();
this.loading = false;
},
error: error => {
// handle error
}
})
);
}
ngAfterViewInit(): void {
this.loading.next(true); // <-- push `true`
}
这真的取决于你到底想做什么,但你可以合并 EMPTY
:
import { EMPTY } from 'rxjs';
...
this._messageService.loadMyEvent$.pipe(
switchMap(loading => loading ? someObservable : EMPTY),
).subscribe(response => {
// load data
this.loadData();
this.loading = false;
});