繁体   English   中英

组件初始化Angular中一个又一个运行方法

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM