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

Is it possible to access BreakpointObserver in Angular Material before the page has finished loading?

When utilizing the Angular BreakpointObserver in combination with Angular Material, I encounter an issue where the observer only triggers a change after it detects a difference. This becomes problematic on initial page load as there is no existing change t ...

Angular - failure to detect function execution by spy

I've been trying to test a feature module, but I'm facing some difficulties. The last test is failing because the spy isn't detecting that the method is being called, even when I move the this.translate.use(this.currentLanguage.i18n) call ou ...

Exploring TypeScript: Implementing a runtime data mapping in place of an interface

Take a look at this code snippet that defines two command handlers for a server: import { plainToClass } from "class-transformer"; enum Command { COMMAND_1, COMMAND_2, } class Command1Data { foo1!: string } class Command2Data { foo2!: ...

Getting a specific array from the API with fetch in Angular: A step-by-step guide

I am trying to retrieve images from an API, but I'm having trouble accessing all the arrays to get to the data. Currently, I am only able to fetch the posts arrays in a single call and not beyond that. https://i.stack.imgur.com/aFWlD.jpg My method fo ...

Implementing Angular 2 - Steps to ensure a service is accessible within the app module

I'm running into an issue trying to utilize a function within a service that I believed was globally accessible. The service in question is named SavedNotificationService: import { Injectable } from '@angular/core'; @Injectable() export cl ...

Tips for fixing TypeScript compiler error TS2339: Issue with accessing 'errorValue' property in Angular 5 project

Within a component, I have developed a function to manage errors returned from a Rest Service and determine the corresponding error message to display to the user. This method accepts an error object (custom data structure from the service), navigates to e ...

How to update nested properties in Typescript using bracket notation

Imagine there is an interface and object with nested properties as shown below: interface Iobj { a: { a2:string }; b: string; } const obj: Iobj = { a:{ a2: "hello" } b: "world" }; Now let's say we have strings that ...

"Sending the selected pass selector as a parameter to the dispatched action is causing a typing

When a selector changes its value, I want to trigger an action. To achieve this, I passed the selector with a subscription instead of passing an observable. selectedSchedulingsOnPopup$ = this.store.pipe(select(selectSchedulingsByBranch)); this.store.disp ...

Utilizing React and TypeScript: Passing Arguments to MouseEventHandler Type Event Handlers

Can you help me understand how to properly define the event handler handleStatus as type MouseEventHandler, in order to pass an additional argument of type Todo to the function? interface TodoProps { todos: Array<Todos> handleStatus: Mous ...

Organize and display a list of contacts alphabetically by the first letter of their

I have a list of contacts that I need help with. Despite searching on Stack Overflow, I couldn't find the answer. Can someone please assist? Thank you. export const rows = [ { id: 1, name: 'Snow', email: 'Jon', co ...

Issue with Sending Messages using SignalR in .NET and Angular

I am attempting to make a simple SignalR example work, following Microsoft's tutorial and using the Weatherforecast .NET/Angular SPA from Visual Studio as a starting point for a project I plan to integrate SignalR with in the future. You can find the ...

When canActivate returns false, the screen in Angular 2 will still be accessed

I am encountering a problem where my canActivate method is returning false, but still navigating to the blocked screen. This issue seems to only occur in Chrome, as everything works fine in IE. Here is how the canActivate method looks: canActivate(route: ...

Unable to execute OAuth2 with Okta using angular-oauth2-oidc framework

Looking to create an authentication module for an Angular application using Okta as the identity provider and implementing the angular-oauth2-oidc flow. Following a guide here: . However, encountering errors when running the web app. How can I troubleshoot ...

What seems to be the issue with the useState hook in my React application - is it not functioning as

Currently, I am engrossed in a project where I am crafting a Select component using a newfound design pattern. The execution looks flawless, but there seems to be an issue as the useState function doesn't seem to be functioning properly. As a newcomer ...

Protractor fails to capture the presence of mat-dialog-container

My Protractor test for an Angular 5 application is functioning well, except when it has to handle a popup containing input fields. The HTML element representing the popup looks like this: <mat-dialog-container class="mat-dialog-container ng-tns-c26-5 n ...

The data type 'boolean' cannot be assigned to the type 'CaseReducer<ReportedCasesState, { payload: any; type: string; }>'

I recently developed a deletion reducer using reduxjs/toolkit: import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { AppThunk } from "../store"; import { ReportedCase, deleteReportCase } from "../../api/reportedCasesApi"; import history ...

Q.all failing to execute promises within array

Hey all, I'm currently facing an issue while attempting to migrate users - the promises are not being called. User = mongoose.model 'User' User.find({"hisId" : {$exists : true}}).exec (err, doc)-> if err console.error err ...

Confirm that a specific value exists within an enumerated set

I am currently using Angular 13.3.9 and typescript 4.6.4. My main objective is to determine if a value is referencing an enum. Below is the code snippet: export enum HttpFunctionalErrorCodes { ACCOUNT_NOT_FOUND = 'ACCOUNT_NOT_FOUND', USER_ ...

Angular array sanitization for handling multiple URLs

I need to sanitize multiple URLs from an array containing links to video sites e.g.: videos: SafeResourceUrl = ['www.someURL1', 'www.someURL2',... ]; To achieve this, I created a constructor like so: constructor(private sanitizer ...

Using JSDoc to Include TypeScript Definitions

I've been attempting to utilize the ts-xor package, which provides a TypeScript definition: export declare type XOR<T, U> = (T | U) extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U; This is how I'm imp ...