该问题的解决方法是使用exhaustMap替代switchMap。exhaustMap等待前一个内部Observable完成后才会触发下一个内部Observable,并忽略中间的值。这确保了我们始终使用最新的值。
代码示例:
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { exhaustMap, map } from 'rxjs/operators';
import { Store } from '@ngrx/store';
import { AppState } from './app.state';
@Component({
selector: 'app-root',
template: `
{{ title$ | async }}
`,
})
export class AppComponent implements OnInit {
title$: Observable;
constructor(private store: Store) {}
ngOnInit() {
this.title$ = this.store.select('title').pipe(
exhaustMap((title) => {
return this.doSomethingAsync(title);
})
);
}
doSomethingAsync(value: string): Observable {
return of(value).pipe(
delay(1000),
map((title) => {
return `Hello ${title}!`;
})
);
}
}