[英]Run method after another has been finished in component initialization Angular
在我的組件初始化方法中,我要在initMap()
完成之后運行addCutomLayers()
方法。
我想在我下面的代碼ngOnInit()
但由於某種原因,在我的瀏覽器的調試器,我可以看到initMap()
仍與同時運行addCustomLayer()
this.initMap().then(res => {
if (this.selectedCustomLayers) {
this.customLayerService.addCustomLayers()
.takeUntil(this.destroy$)
.subscribe(result => {
})
}
});
//this method is in customLayerService service
public addCustomLayers(): Observable<any> {
//some Code
}
private initMap() {
return new Promise((resolve, reject) => {
//some code
resolve()
});
}
也許首先嘗試將promise轉換為rxjs可觀察的。 這也將使添加一些日志記錄變得更加容易,以查看initMap是否在您期望的時候返回值/大理石。 然后,您還可以查看使用switchMap(如果需要,則使用mergeMap)並使用filter代替if語句。 盡管對於過濾器,如果適用的話,使用initMap返回值中的值會更清潔。
import { from } from 'rxjs';
import { filter, switchMap, takeUntil, tap } from 'rxjs/operators';
from(this.initMap()).pipe(
tap(res => console.log('init map tick')),
filter(_ => this.selectedCustomLayers),
switchMap(r => this.customLayerService.addCustomLayers().pipe(takeUntil(this.destroy$)))
).subscribe(res => { };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.