Javascript 在组件初始化中完成另一个之后运行方法

Javascript 在组件初始化中完成另一个之后运行方法,javascript,angular,observable,Javascript,Angular,Observable,在我的组件初始化方法中,我想在initMap()完成后运行addCutomLayers()方法 我在我的ngOnInit()中尝试了下面的代码,但由于某种原因,在我的浏览器调试器中,我可以看到initMap()仍然与addCustomLayer()同时运行 this.initMap().then(res=>{ 如果(此。selectedCustomLayers){ this.customLayerService.addCustomLayers() .takeUntil(此.destroy$) .

在我的组件初始化方法中,我想在
initMap()
完成后运行
addCutomLayers()
方法

我在我的
ngOnInit()
中尝试了下面的代码,但由于某种原因,在我的浏览器调试器中,我可以看到
initMap()
仍然与
addCustomLayer()同时运行

this.initMap().then(res=>{
如果(此。selectedCustomLayers){
this.customLayerService.addCustomLayers()
.takeUntil(此.destroy$)
.订阅(结果=>{
})
}
});    
//此方法位于customLayerService服务中
public addCustomLayers():可观察{
//一些代码
}
私有initMap(){
返回新承诺((解决、拒绝)=>{
//一些代码
解决()
});
}

可能先尝试将承诺转换为rxjs observable。 这样还可以更容易地添加一些日志记录,以查看initMap是否在您期望的时候返回值/marble。 然后,您还可以考虑使用switchMap(或者mergeMap,如果愿意的话)和使用filter而不是if语句。尽管对于过滤器来说,使用initMap返回值中的值(如果适用)会更干净

从'rxjs'导入{from};
从“rxjs/operators”导入{filter、switchMap、takeUntil、tap};
来自(this.initMap()).pipe(
点击(res=>console.log('init map tick')),
过滤器(=>this.selectedCustomLayers),
switchMap(r=>this.customLayerService.addCustomLayers().pipe(takeUntil(this.destroy$))
).subscribe(res=>{};
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()
  });
}