在我的ngOnInit中,我想等待所有fetchLists的請求完成后再繼續進行。
因此我們有兩個步驟:
- 第1步:以任何順序/并行地獲取所有串列 。
- 第 2 步:一旦第 1 步完成,繼續執行自己的邏輯,其中包括另一個訂閱...... 。
ngOnInit()。void {
//step 1: 以任何隨機順序獲取所有串列。
this.fetchLists()。
//step 2: 一旦完成,繼續進行邏輯處理。
this.route.params。 subscribe(span class="hljs-params">params =>。
if (params[`id`] ) {
this.isNew = false;
this.httpHandler.getUser(params[`id`] )
.subscribe(span class="hljs-params">user => this.user = user
} else {
this.isNew = true;
});
}
fetchLists()。void {
this.httpHandlerCached.getListsA()
.subscribe(listA => this.listA = listA) 。
this.httpHandlerCached.getListsB()
.subscribe(listB => this.listB = listB) 。
this.httpHandlerCached.getListsC()
.subscribe(listC => this.listC = listC) 。
}
上面的代碼有一個問題,就是第2步不會等待第1步完成。
我唯一的解決方案包括在合并步驟 1 和步驟 2 時使用 forkjoin 或 combinelatest。而這是我真正需要避免的事情。第1步和第2步必須在不同的方法中。
因此,使用 forkjoin 或 combinelatest 的建議想法并不是令人滿意的解決方案:
//Solution 1: forkJoin "merging" step 1 and step 2 in one big codeeblock
ngOnInit()。void {
forkJoin([
this.httpHandlerCached.getListsA()。
this.httpHandlerCached.getListsB() 。
this.httpHandlerCached.getListsC() 。
this.route.params。 pipe(take(1))
]).subscribe(span class="hljs-params">res => {
this.listA = res[0] 。
this.listB = res[1] 。
this.listC = res[2] 。
if (res[3][`id`] ) {
this.isNew = false;
this.httpHandler.getUser(res[3][`id`] )
.subscribe(user => this.user = user) 。
} else {
this.isNew = true;
}
});
}
//Solution 2: combineLatest "merging" step 1 and step 2 in one big codeblock[/span] 。
ngOnInit()。void {
combineLatest([
this.httpHandlerCached.getListsA()。
this.httpHandlerCached.getListsB() 。
this.httpHandlerCached.getListsC() 。
this.route.params.
]).subscribe(span class="hljs-params">res => {
this.listA = res[0] 。
this.listB = res[1] 。
this.listC = res[2] 。
if (res[3][`id`] ) {
this.isNew = false;
this.httpHandler.getUser(res[3][`id`] )
.subscribe(user => this.user = user) 。
} else {
this.isNew = true;
}
});
}
同樣,在上述解決方案中,步驟1和步驟2都只是放在一起。然而,我需要在一個單獨的方法中獲取串列,如上面的 "fetchList()",我只想在進行步驟2之前等待它的完成。
uj5u.com熱心網友回復:
你可以這樣使用forkJoin
forkJoin([
this.httpHandlerCached。 getListsA().pipe(first())。
this.httpHandlerCached。 getListsB().pipe(first())。
this.httpHandlerCached。 getListsC().pipe(first()
]).subscribe(([listA, listB, listC]/span>) => {
this.listA = listA;
this.listB = listB;
this.listC = listC;
//現在設定路由器訂閱。
this.initRouter()。
})
initRouter(){
///做某事。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/332364.html
標籤:
上一篇:讓管道在angular中自我重繪
