[英]Run method after another has been finished in component initialization Angular
In my component initialization method I want to run addCutomLayers()
method after initMap()
has been finished. 在我的组件初始化方法中,我要在
initMap()
完成之后运行addCutomLayers()
方法。
I tried the code below in my ngOnInit()
but for some reason in my browser debugger I can see that the initMap()
is still running simultaneously with the addCustomLayer()
我想在我下面的代码
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()
});
}
Maybe try converting the promise to rxjs observable first. 也许首先尝试将promise转换为rxjs可观察的。 This'll also make it easier to add some logging to see if the initMap is returning a value/marble when you expect it.
这也将使添加一些日志记录变得更加容易,以查看initMap是否在您期望的时候返回值/大理石。 You can then also look at using a switchMap (or mergeMap if that's preferred) and using filter instead of the if statement.
然后,您还可以查看使用switchMap(如果需要,则使用mergeMap)并使用filter代替if语句。 Although for the filter it would be cleaner to use a value from the initMap return values if that's applicable.
尽管对于过滤器,如果适用的话,使用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.