簡體   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