I have a root service that has composition inside like:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class MapService {
private rmap: RMap;
init(props: Props) {
this.rmap = new RMap(props);
}
getMapLayers() {
return this.rmap.layers;
}
}
Problem is that new RMap();
has inside async functions. And when I use getMapLayers()
from service it gives me error as undefined
, because some functionality inside new RMap()
are not ready. They are async.
How to solve this more properly?
As I mentioned above I get props from input:
@Input() props: Props;
constructor(private rMap: RMap) {
this.rMap.init(this.props) {
}
}
But in anothe root service I get undefined on the line this.rMap.interactiveMap.getSourceId();
:
@Injectable({ providedIn: 'root' })
export class SearchyService {
constructor(private rMap: RMap) {
this.drawResourceId = this.rMap.interactiveMap.getSourceId();
}
}
Because RMap
has some async.
You have to use async/await
for this, or the promise.then
in order to wait for the function to be ready.
Something like this:
async getMapLayers() {
await this.map.getLayers()
}
And the place the you are calling the this function, will be like this:
async gettingLayers() {
this.mapService.init();
await this.mapService.getMapLayers()
}
You can read more about Promises here: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.