Tre*_*tni 0 http-get observable async-await rxjs typescript
这个问题已经出现过好几次了,每次出现时,我都会忙着弄清楚如何以正确的方式去做,因为我似乎永远无法找到上次需要时是如何做的。
这次出现是因为我意识到httpGet在处理先前的httpGet调用时需要进行额外的调用:
http.getWrapper<T>(whatever)
.pipe<T, T>(map<T, T>(res => getWrapper2<T, T>(res)) // New function, returns the same type it was given
.pipe<T, U>(oldStuff)
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是,以前,没有额外的get调用,我的oldStuff处理程序收到了一个T它可以毫无问题地处理的问题。但是新的get调用返回一个Observable<T>,我总是发现弄清楚如何告诉管道链等待 完成get并使用最终值很令人困惑。我能想到做的任何事情,主要似乎是toPromise()和的变体async/await,只是在我和我的数据之间移动额外的层,而我似乎不太能理解它。由于某种原因,插入第二个get似乎总是比第一个更令人困惑get,我不知道我是否需要改变结构,或者只是我的想法不对。
为了让事情变得更加混乱,只有有时才需要额外的处理层:
.pipe(map(res => condition(res) ? getWrapper2(res) : res))
Run Code Online (Sandbox Code Playgroud)
我可以做什么来等待并扁平化它,以便我可以将新get结果传递给链的其余部分pipe?
你正在寻找high order observables
最受欢迎的运算符:
mergeMap, switchMap,concatMap
这些运算符应该返回 observable,在下一步中您将收到数据
import { of } from 'rxjs';
import { map, mergeMap } from 'rxjs/operators';
const initialApiCall = () => of('initialApiCall');
const extraApiCall = (res) => of(res + '_' + 'extra result'); // getWrapper2
const condition = (res) => !res;
initialApiCall()
.pipe(
mergeMap((res) => (condition(res) // checking condition
? extraApiCall(res) // api call
: of(res)) // should convert privitive data to observable
),
map((data) => console.log(data)) // here you will have result of `extraApiCall` or `res`
)
.subscribe();
Run Code Online (Sandbox Code Playgroud)
演示:
https://stackblitz.com/edit/rxjs-suryq3?file=index.ts
| 归档时间: |
|
| 查看次数: |
609 次 |
| 最近记录: |