Methods for uploading information and delivering promise?

In my model class, I have the following methods:

export class Model {
  constructor(public model: any, public repository: RepositoryService) {
  }

   public hasChildren(id: number) {
        return this.model.childs && this.model.findIndex((opt) => opt.id == id) == -1;
    }

    public getChildren(id: number): Promise<any> {
      return new Promise((resolve, reject) => {
        if (this.hasChildren(id)) {
            resolve(this.model.childs);
        } else {
          this.repository.loadChildren().subscribe((response) => {
            resolve(response);
          })
        }
      });
    }
}

// Create instance

this.model = new Model(dataModel, this.repositoryService);

When trying to retrieve data or load it if it is not in the model:

this.model.getChildren(value).then((data) => {
   console.log(data);
});

I am facing an issue with the

public getChildren(id: number): Promise<any>
method. How can I correctly utilize promises in this context?

Answer №1

Instead of creating a Promise object when you're not rejecting it, consider using async/await syntax like below:

async fetchKids(id: number): Promise<any> {
    if (this.hasKids(id))
       return (this.model.children)
    return (await this.repo.fetchChildren().toPromise())
}

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

The Three.js OBJ loader is not functioning as expected when implemented in TypeScript within an Angular project

Require 'three-obj-loader'; Create a new instance of THREEObjLoader using the THREE library. The issue is that objLoader is showing up as undefined. Any ideas on why this could be happening? If anyone has insight into why the object instance i ...

Unable to receive a response from the HttpClient

I've encountered an issue while trying to manage error responses from my API. What I expect to receive: What I'm actually receiving: My service.ts: import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { Inject ...

I am trying to show my <app-home></app-home> component only once during initialization, but it is displaying on all the component pages. How can I fix this issue?

After attempting all the examples provided on Stack Overflow, I am still encountering numerous errors and my code is not executing as desired. Can someone please provide me with a code snippet and explanation on how to add a component only during initial ...

Exploring the Concept of Dependency Injection in Angular 2

Below is a code snippet showcasing Angular 2/Typescript integration: @Component({ ... : ... providers: [MyService] }) export class MyComponent{ constructor(private _myService : MyService){ } someFunction(){ this._mySer ...

What caused the mat-date calendar style to malfunction?

I integrated mat-date into my Angular project, but encountered an issue where the styles of the calendar were not displaying properly when clicking the icon. Here is the displayed calendar effect I attempted to troubleshoot by commenting out the styles o ...

Issue: "Unable to determine all arguments for the constructor of e: (?)."

After deploying to github-pages with angular-cli, I encountered this error: Error: "Can't resolve all parameters for e: (?)". The application works fine locally. How can I identify the source of the issue? I've tested it with both angular-cl ...

Using Angular to pass a variable in nth-child with CSS

I am trying to pass a variable from the model ts into a specific nth-child element, but I am struggling with how to accomplish this. My current code snippet looks like this: ts model: @Input() public limit: number scss: .collapsed-list { max-height:15r ...

The variable X has been defined, but it's never actually utilized. Despite declaring it, I have not accessed its

I have encountered warnings in VSCode while using certain properties in my Angular component. The warnings state: '_id' is declared but its value is never read.ts(6133) (property) ItemEditComponent._id: number | undefined '_isModeEdit' ...

Removing click functionality in Angular 2 when utilizing [innerHTML]

Currently, I need to include HTML in my TypeScript file using the [innerHTML] tag within the template. I am attempting to add a click function within the HTML: status = "<img src='assets/hello.png' (click)='hello()' />"; Howeve ...

I'm having trouble managing state properly in Safari because of issues with the useState hook

Encountering Safari compatibility issues when updating a component's state. Though aware of Safari's stricter mode compared to Chrome, the bug persists. The problem arises with the inputs: https://i.sstatic.net/WSOJr.png Whenever an option is ...

Transforming Post Requests into Options Requests

I am facing an issue with my Angular 6 API. After creating interceptors, my POST requests are turning into OPTIONS requests. What could be causing this problem? Here is the code for one of the Services: import { Injectable } from '@angular/core&apo ...

In Typescript, what sets apart a generic written before a function compared to after a type declaration?

Can you explain the difference between these two type declarations for arrow functions? export type Sort = <D>(r: Rows<D>, f: Field<D>, o: Order) => Rows<D>; export type Sort<D> = (r: Rows<D>, f: Field<D>, o: ...

The module '@angular/compiler' is missing and cannot be located at this time

Upon running the command npm install -g @angular/cli and attempting to run my application, I encountered an error message in the terminal stating that it could not find the module '@angular/compiler'. How can I include the compiler in my package. ...

Maintain the URL state while logging in using angular-oauth2-oidc

In our Angular application, we utilize angular-oauth2-oidc for authentication management with the Code Flow and PKCE. To enable automatic login for users upon app visit, we initialize our app as follows: this.oauthService.configure(authModuleObject); this. ...

Error: Angular - encountering undefined response when making HTTP request

When making a HTTP GET request to my backend, it returns the following JSON data: "{\"instID\":\"2018#10#30\",\"procID\":1161006,\"threadNum\":0,\"status\":2}", "{\"instID\":\"2018#1 ...

Which is the optimal choice: subscribing from within a subscription or incorporating rxjs concat with tap?

After storing data in the backend, I proceed to retrieve all reserved data for that specific item. It is crucial that the data retrieval happens only after the reservation process to ensure its inclusion. Presented with two possible solutions, I am cont ...

The 'ng-scroll' component does not have a defined @viewchild

I am encountering an issue where the dayavailablescroll reference is showing as undefined in the ngAfterViewInit method. <div class="shifts-rightTable " style="background-color: yellow" [ngClass]="{'tab-active':availDa ...

What is the correct way to effectively integrate react-hook-form with redux and typescript?

After tirelessly searching for a comprehensive guide that could demonstrate all these requirements in one example, I eventually resorted to brute force to make something functional. However, I am well aware that this approach is not the correct way to achi ...

create an endless loop to animate in angular2

Is there a way to add iterations, or something similar to the ccs3 animation-iteration-count in Angular 2 animations? I've looked but can't find anything related. How can we apply an infinite play to the animation? Where should we include that o ...

Is there a way to position the profile image input on the right side of the label, using "choose image" instead of "choose file"?

In the process of creating a teacher form, I am looking to allow users to select images from a gallery for their profile. The goal is to reposition and relabel the "choose image" button on the right side with the label "Choose Image," while having the la ...