需要在 switchMap() 函数中使用 timer(),使其等待 setInterval() 的结果后再进行下一步操作。 代码示例如下:
import { timer } from 'rxjs'; import { switchMap } from 'rxjs/operators';
// 使用 timer() 替换 setInterval(),并在 switchMap() 中等待结果 timer(0, 1000).pipe( switchMap(() => { return http.get('api/data'); }) ).subscribe(data => { console.log(data); });
// 或者使用 Promise 和 async/await: async function getData() { const result = await timer(0, 1000).toPromise(); const data = await http.get('api/data').toPromise(); console.log(data); }
getData();