[英]How to configure service in Angular?
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();
问题是
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.当我从服务中使用
getMapLayers()
时,它会给我错误undefined
,因为new RMap()
中的某些功能尚未准备好。 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();
但是在另一个根服务中,我在
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.因为
RMap
有一些异步。
You have to use async/await
for this, or the promise.then
in order to wait for the function to be ready.为此,您必须使用
async/await
或promise.then
以等待 function 准备就绪。
Something like this:像这样的东西:
async getMapLayers() {
await this.map.getLayers()
}
And the place the you are calling the this function, will be like this:而你调用这个 function 的地方将是这样的:
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您可以在此处阅读有关 Promises 的更多信息: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.