"Setting Up a Service in Angular: A Step-by-Step Guide

I am facing an issue with a root service that contains composition within it, as shown below:

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

}

The problem arises because new RMap(); includes async functions. When I call the getMapLayers() method from the service, I encounter an error of undefined, since some functionalities within new RMap() are not yet ready due to being asynchronous.

What would be a proper solution to this?

As mentioned earlier, I receive props through input:

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

However, in another root service, I face the issue of receiving undefined on the line

this.rMap.interactiveMap.getSourceId();
:

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

This is because RMap involves some asynchronous operations.

Answer №1

To ensure the function is ready, utilize async/await or promise.then.

An example implementation would be:

async fetchUserData() {
    await this.api.getUserData()
}

To call this function, follow this pattern:

async retrievingData() {
  this.dataService.initialize();
  await this.dataService.fetchUserData()
}

Further information on Promises can be found at: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Limit function parameter types to object keys

Is it possible to constrain my function parameter to match the keys of an object? I want to achieve something similar to this: export const details = { x: { INFO_x: 'xxx' }, y: { I ...

Encounter a 404 error message coming from nginx while running ng build

Hello, I'm new to angular and attempting to run my angular application within a docker container. After executing ng build or ng build -prod and setting it up to run in a docker using the following dockerfile: ### STAGE 1: Build ### FROM node:12.7-a ...

Customized configuration and Ahead-of-Time compilation for modules and services

I am facing a challenge where I need to configure Angular services dynamically based on a runtime switch. In the past, when AOT was not in place, I managed to make it work using the code snippet below: @NgModule({ imports: [HttpModule], providers: [] ...

What is the method for generating a button with a boolean value and a unique identifier?

I am currently working on coding a component for displaying documentation similar to qt doc (https://doc.qt.io/qt-5/qstring.html) utilizing CodeMirror to showcase code examples. My implementation is in Angular 2: <div *ngFor="let method of methods" st ...

Unable to find and load the specified css-font formats (svg, eot, woff, woff2, and ttf) using webpack

Looking to incorporate a unique font into my project: @font-face { font-family: 'bikeshop'; src: url('/src/styles/bikeFont/font/bikeshop.eot?37006833'); src: url('/src/styles/bikeFont/font/bikeshop.eot?37006833#iefix') ...

Obtain data from a local JSON file using the http.get() method in Angular 2

I am attempting to utilize the http.get() method in Angular 2 to load a local JSON file. I followed a suggestion from Stack Overflow that involves modifying my app.module.ts: In this example, I have imported the HttpModule and the JsonModule from @angular ...

What is the best method to add information into an array using Angular 7?

My data consists of an array of objects : [ { indicatorDatasource: "trackingError", un_an: 0, trois_ans: 0, cinq_ans: 0 }, { indicatorDatasource: "annualisedFundPerformance", un_an: 19.749642029434945, trois ...

Utilizing Typescript for directive implementation with isolated scope function bindings

I am currently developing a web application using AngularJS and TypeScript for the first time. The challenge I am facing involves a directive that is supposed to trigger a function passed through its isolate scope. In my application, I have a controller r ...

The RemoveEventListener function seems to be malfunctioning within Angular2 when implemented with TypeScript

I am currently incorporating three.js into Angular2. The code I am using is quite straightforward, as shown below. this.webGLRenderer.domElement.addEventListener('mousedown', ()=>this.onMouseDown(<MouseEvent>event), false); this.webGLR ...

Using Swiper in an Angular 8 application

I've been working on integrating Swiper into my Angular 8 project: . I've added a javascript file to my assets folder and included it in my angular.json. In addition, I've imported Swiper in my app.module.ts file and executed npm install @ ...

Storing the subscription value retrieved from an API in a global variable

I am trying to find a way to make the data retrieved from an API accessible as a global variable in Typescript. I know that using subscribe() prevents this, so I'm looking for a workaround. Here is the API code: getResultCount(category:any):Obs ...

Alerts appear immediately upon beginning to type, asking for 8 characters and ensuring both passwords match

Is it possible to notify users that both passwords should match and they need to enter at least 8 characters after typing? There is currently an issue where a notification appears for entering less than 8 characters, but the password reset still proceeds ...

Receiving a blank response after making a post request even though the request was processed without

While making a post request using httpClient, I am receiving a null response despite the request being processed successfully. File: serviceClass.ts this.httpOptions = { headers: new HttpHeaders( { 'Content-Type': 'application ...

What is the best way to deploy a docker image from my computer to the office server?

I have an Angular project that has been Dockerized on my personal computer. I am now looking to deploy it on my company's server without having superuser permissions. What steps should I take to achieve this? ...

Deactivate the button until the input meets validation criteria using Angular

What I'm trying to achieve is to restrict certain input fields to only accept integer or decimal values. Here's the code snippet that I currently have: <input type="text" pattern="[0-9]*" [(ngModel)]="myValue" pInputText class="medium-field" ...

Experience the convenience of selecting multiple rows with checkboxes, while enjoying the simplicity of selecting a single row by clicking

Hey there! I'm looking to enable multiple selection using checkboxes and single selection by clicking on a row. Does anyone know how I can achieve this within the same table? Check out this link for some ideas ...

Tips on sorting through an array using Angular 11 and data

I'm working on a subpage that contains a large amount of detailed data in the form of thousands of records. I want to filter this data based on the "id" from my route, which is also included in the dataset. However, I've run into some difficultie ...

Disallow negative numbers but allow decimals in HTML input

I need help restricting user input to prevent negative numbers while still allowing floating point numbers in my Angular project. Any suggestions using Angular tools would be greatly appreciated. Thanks! ...

What is the best way to access the rendered child components within a parent component?

I am seeking a way to retrieve only the visible child components within a parent component. Below is my unsuccessful pseudo-code attempt: parent.component.html <parent (click)="changeVisibility()"> <child *ngIf="visible1"></child> ...

Explore an example of using custom controls in a FormArray within an Angular 5 reactive form on StackBlitz

Check out my sample project on stackblitz that tests nesting components and retrieving the complete form value. https://stackblitz.com/edit/mensand-hobbies-football-tennis This is a demonstration where I aim to utilize different components stored in an a ...