繁体   English   中英

Angular中如何配置服务?

[英]How to configure service in Angular?

我有一个根服务,其中包含如下组成:

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;
  }

}

问题是new RMap(); 具有内部异步功能。 当我从服务中使用getMapLayers()时,它会给我错误undefined ,因为new RMap()中的某些功能尚未准备好。 它们是异步的。

如何更妥善地解决这个问题?

正如我上面提到的,我从输入中获得道具:

@Input() props: Props;
constructor(private rMap: RMap) {
  this.rMap.init(this.props) {
 } 
}

但是在另一个根服务中,我在this.rMap.interactiveMap.getSourceId();

@Injectable({ providedIn: 'root' })
export class SearchyService {
    constructor(private rMap: RMap) {
        this.drawResourceId = this.rMap.interactiveMap.getSourceId();
    } 
}

因为RMap有一些异步。

为此,您必须使用async/awaitpromise.then以等待 function 准备就绪。

像这样的东西:

async getMapLayers() {
    await this.map.getLayers()
}

而你调用这个 function 的地方将是这样的:

async gettingLayers() {
  this.mapService.init();
  await this.mapService.getMapLayers()
}

您可以在此处阅读有关 Promises 的更多信息: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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