How to specify the return type of a promise from an observer in Angular 6

Typically, I prefer using observables. However, in order to avoid 'callback hell' in this particular scenario, I decided to use toPromise(). Unfortunately, I encountered a lint error message when trying to define the return type:

The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? Type 'Object' is missing the following properties from type 'ReferralReasons[]': length

Here is my code (this.apiSvc.get returns the http.get object):

async getJobReferralReasons(): Promise<Array<ReferralReasons>> {
    return this.apiSvc.get(`${this.API_JOB}/ReferralReasons`).toPromise();
}

However, the error disappears when I use:

async getJobReferralReasons(): Promise<any> {
    return this.apiSvc.get(`${this.API_JOB}/ReferralReasons`).toPromise();
}

As a result, when I call it, I receive the array of referral codes directly in an array:

const reasons = await this.helpdeskSvc.getJobReferralReasons();

I assumed that changing any and setting the type to Array<ReferralReasons> would work. What am I missing in setting the correct type?

---Update

This is how my service call looks like:

get(apiURL, data = {}) {
    return this.http.get(this.parseURL(apiURL), {
        headers: this.getHeaders(),
        params: this.parseGetParams(data)
    });
}

While this works, it's not exactly what I intended (slightly different and unable to specify the type before the get method):

async getJobReferralReasons2(): Promise<ReferralReasons[]> {
    return this.http.get<ReferralReasons[]>('', {}).toPromise();
}

Answer №1

To ensure that the promise recognizes the HTTP get call, make sure to specify the expected return type.

For instance:

apiSvc uses T template for the type.

get<T>(apiURL, data = {}) {
  return this.http.get<T>(this.parseURL(apiURL), {
      headers: this.getHeaders(),
      params: this.parseGetParams(data)
  });
}

component specifies the actual type:

async getJobReferralReasons(): Promise<Array<ReferralReasons>> {
    return this.apiSvc.get<Array<ReferralReasons>>(`${this.API_JOB}/ReferralReasons`).toPromise();
}

Alternatively:

async getJobReferralReasons(): Promise<ReferralReasons[]> {
    return this.apiSvc.get<ReferralReasons[]>(`${this.API_JOB}/ReferralReasons`).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

Sharing information from Directive to Component in Angular

Here is a special directive that detects key strokes on any component: import { Directive, HostListener } from '@angular/core'; @Directive({ selector: '[keyCatcher]' }) export class keyCatcher { @HostListener('document:keydo ...

The ngmodel variable is not responding to dynamic changes

I'm currently working on dynamically changing a date and getting it to reflect in the view, but for some reason it's not showing up. When the date is hard-coded in an array like this, it works perfectly fine and shows up in the view. My date : Ar ...

Having difficulty selecting an item from the MaterialUI package

While trying to utilize the MaterialUI Select component with typescript/reactjs, I encountered an issue during the instantiation of the Select element. The error message I'm receiving states: Type 'Courses' is missing the following properti ...

When using the ngFor directive, the select tag with ngModel does not correctly select options based on the specified

Issue with select dropdown not pre-selecting values in ngFor based on ngModel. Take a look at the relevant component and html code: testArr = [ { id : '1', value: 'one' }, { id : '2', ...

The test function is not recognized by Cordova when the device is ready

Within my app.component.ts file, I have the following code snippet: export class AppComponent implements OnInit { constructor(private auth: AuthService, private fireBaseService: FirebaseService, ) {} ngOnInit() { this.auth.run(); document.addE ...

Issue TS2315: Type 'ElementRef' does not support generics

While attempting to integrate @angular/materials into my application, I encountered a successful compilation with the following error messages: webpack: Compiled successfully. ERROR in node_modules/@angular/material/button-toggle/typings/button-toggle.d.t ...

Vue encountered a double loading issue when utilizing a library compiled with Webpack

I am facing an issue with my TypeScript library of Vue components that gets compiled into a single JS file using Webpack. The problem arises when the TypeScript project consuming this library also depends on Vue. Upon running the application, I noticed tha ...

The variable is currently undefined because it has an array assigned to it

Upon selecting multiple checkboxes for variants, I am retrieving checked data using the following method: get selectedIdsFromViolCategoriesFormArray(): string[] { return this.violCategories .filter((cat, catIdx) => this.violCategoriesFormArr. ...

When the page is reloaded, establish the default value for the dropdown in Angular 9

My HTML file includes the use of p-dropdown: <p-dropdown id="userType" name="userType" inputId="userType" formControlName="userType" [required]="true" [tabindex]="1" optionLabe ...

The ngtools/webpack error is indicating that the app.module.ngfactory is missing

I'm currently attempting to utilize the @ngtools/webpack plugin in webpack 2 to create an Ahead-of-Time (AoT) version of my Angular 4 application. However, I am struggling to grasp the output generated by this plugin. Specifically, I have set up a ma ...

How to pull data from an HTTP source without relying on promises

Here is a simplified version of the service code I am using: Load(Channel: any) { // let URL = Globals.AppSiteRoot + Channel.URL return this.LoadData(URL) } Load_Default() { let URL = Globals.AppSiteRoot + "di ...

ngFor directive not iterating properly without any errors being displayed in the console

I reviewed numerous inquiries about issues with "ngFor not functioning properly". Here are the specifics. app.modules.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; impo ...

When using TypeScript, how can I effectively utilize the Component property obtained from connect()?

Software Development Environment TypeScript 2.8 React 16 Redux Foo.tsx interface IFooProps{ userId:number } class Foo extends Component<IFooProps>{ render(){ return <p>foo...</p> } } const mapStateToProps = (state: I ...

How to start Angular2 prototype with an object literal

export abstract class GridColumn { public field?: string; public sortField?: string; public header?: string; public footer?: string; public sortable?: any = true; public editable?: boolean = false; public filter?: boolean = true ...

Angular TimeTracker for tracking time spent on tasks

I need help creating a timer that starts counting from 0. Unfortunately, when I click the button to start the timer, it doesn't count properly. Can anyone assist me in figuring out why? How can I format this timer to display hours:minutes:seconds li ...

What is the best way to obtain the value of a nested formBuilder group?

Currently, my nested form is structured like this: this.form = this.formBuilder.group({ user: this.formBuilder.group({ id: ['', Validators.required], name: ['', Validators.required], phone: ['' ...

Angular directive problem

Within the module, I have defined a directive but the <div> is not being highlighted as expected. test.directive.ts import { Directive, ElementRef, HostListener, Input } from "@angular/core"; @Directive({ selector: '[test]' }) expor ...

What is the best way to run ng test for all components within a sub module of an Angular application?

In my Angular application, I have defined the app module as follows: app.module.ts export class AppModule {} I am able to execute tests using ng test MyApp Within this application, I also have multiple modules set up like so: my-one.module.ts / my-oth ...

Identified the category

How can I retrieve the default option from a list of options? type export type Unpacked<T> = T extends Array<infer U> ? U : T; interface getDefaultValue?: <T extends Option[]>(options: T) => Unpacked<T>; Example const options = ...

What is the process for defining the type or interface of an object in Visual Studio Code?

Is there a way to create a new type or interface by replicating the structure of a complex object that is imported from a library? For instance, in the image below, the object Text is taken from react-three/drei. Upon inspecting the object, I see that it ...