The properties in angular are missing in the type 'Promise<any>'

I encountered an issue while setting up the http connection in my Angular 7 system. The error message popped up when I tried to make a get request:

Type 'Promise<any>' is missing the following properties from type 'User': id, user, email

Here is the relevant code snippet:

export class User { 
  id: number,
  user: string,
  email: string
}

This is how the request was handled:

users: User;

    this.userService.getUsers().subscribe(
          response => {
            if (!response) {
              console.log(Error)
            } else {
              this.users = response
            }
          })

The Http Get method looks like this:

getUsers() {
        return this.service.get(this.endpoint)
        .map((response) => {
            return response;
        });
    }

When it comes to the service, here's what is implemented:

standardHeaders() {
        const headers = new HttpHeaders();
        headers.append('Content-Type', 'application/json');
        if (this.authToken) {
            headers.append('X-Authorization', this.authToken);
        }
        return { headers: headers };
    }

 get(path: string) {
        return this.http.get(this.url + path, this.standardHeaders()).map((response: Response) => {
            return response.json();
        });
    }

path = endpoint

Answer №1

The issue was pinpointed to a simple change in the request code:

users: User;

this.userService.getUsers().subscribe(
      response => {
        if (!response) {
          console.log(Error)
        } else {
          this.users = response
        }
      })

It needed to be replaced with:

this.userService.getUsers().subscribe(
  response => {
    if (!response) {
      console.log(Error)
    } else {
      console.log(response)
      let users : User[] = response
    }
  })

Answer №2

It appears that you are struggling with your code, typically I handle requests like this using HttpClient and a generic GET method.

public get(id: number): Observable<className> {
  return this._http.get<className>(`${this._baseUrl}/${id}`);
}

Then you can utilize it by subscribing to the response like so:

this.service.get(id).subscribe(x => this.myClass = x);

However, in your case, it seems like you are using a service but not utilizing HttpClient, and there is ambiguity surrounding your return type...

Can you clarify whether your getUsers() function returns a single user or multiple users? If it returns a list, you should update your request variable to users: User[];

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

How can I access a TypeScript variable from a global var set in a .cshtml file?

I have defined several variables in my .cshtml file to be used in my angular services: <script> var _APIURL = '@(Url.Content("~/Admin/api/"))'; var _AREAURL = '@(Url.Content("~/Admin/"))'; var _APPURL = &a ...

Typescript: Dynamic return type determined by argument properties

I have a function that should return two different types based on its argument props. interface IPaginateParams { perPage: number; currentPage: number; isFromStart?: boolean; } interface IWithPagination<Data, TParams extends IPaginateParams = IPa ...

What is the best way to iterate through two object keys in TypeScript?

I recently created a Vector class but I am encountering some issues with the syntax. Here is the code snippet: export class Vector { x: number; y: number; constructor(x = 0, y = 0) { this.x = x; this.y = y; } add(v: Vector) { var x ...

NextAuth credentials are undefined and authentication is malfunctioning in React

I encountered the following issue: https://i.sstatic.net/3VBoJ.png This is the code snippet that I am using: return ( <> {Object.values(providers).map((provider) => { if (provider.id === "credentials") { ret ...

What could be causing the error message "Unable to access 'http' property of undefined" to appear in this validator?

Can someone help me with creating an asynchronous validator for a reactive form control that checks if a username already exists? Below is the code for the async validator: userdata.service.ts import { HttpClient } from '@angular/common/http'; i ...

What are some effective measures to defend against a gzip bomb attack on a service

I have a file named test.gzip which contains JSON data. {"events": [ {"uuid":"56c1718c-8eb3-11e9-8157-e4b97a2c93d3", "timestamp":"2019-06-14 14:47:31 +0000", "number":732, "user": {"full_name":"0"*1024*1024*1024}}]} The full_name field in the JSON data c ...

The code compilation of Typescript in a Dockerfile is not functioning as expected due to the error "Name 'process' cannot be found."

Here's the Dockerfile I'm working with: FROM node:latest WORKDIR /usr/src/app ENV NODE_ENV=production COPY package*.json . RUN npm install && npm i -g typescript COPY . . RUN tsc CMD [ "node", "./dist/index.js&qu ...

What is the process for incorporating a personalized inputComponent JSX <input /> into a react-phone-number-input PhoneInput component?

Instructions to follow when working with code. react-phone-number-input provides the option for users to replace its default <input /> JSX tag with a custom one, requiring the type React.ForwardRefExoticComponent<React.InputHTMLAttributes<HTML ...

Storing application state using rxjs observables in an Angular application

I'm looking to implement user status storage in an Angular service. Here is the code snippet I currently have: import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; @Injectable() expo ...

import types dynamically in TypeScript

One of the files I have is called MyFactory.ts. Here is its content: export type CommandFactory = () => string[] | undefined; export enum FactoryIds {commandFactory : 'commandFactory'} Now, my goal is to dynamically import this file into anot ...

What is the process for defining functions with distinct data types while allowing variables to have multiple data types?

I am facing a declaration issue - or rather, a challenge in comprehending Typescript. Let me illustrate the scenario: public migrationSource: Skater | Rink; public migrationDestination: Skater | Rink; public migrationMode: MigrationMode; ngOnInit() { ...

If you want to use the decorators plugin, make sure to include the 'decoratorsBeforeExport' option in your

Currently, I am utilizing Next.js along with TypeScript and attempting to integrate TypeORM into my project, like demonstrated below: @Entity() export class UserModel extends BaseEntity { @PrimaryGeneratedColumn('uuid') id: number } Unfortun ...

The logout feature might refresh the page, yet the user remains logged in

Currently, I am enrolled in a course on Udemy where the instructor is utilizing Angular 2. My task involves building the app using the latest version of Angular. The issue that I am facing pertains to the logout functionality. After successfully logging ou ...

What are the best practices for utilizing *ngIf?

In my Angular project, I am facing a challenge with using *ngIf. My app.component.html file handles both the login page and the dashboard. I want to hide the dashboard until the user logs in. To achieve this, I decided to use *ngIf. Here is how I implement ...

Implementing optional default values in React props using conditional types

I have a dilemma with conditional props types When attempting to set a default value for my optional prop within the conditional type, it causes issues with the types export type ChatBase = { id: string; title: string; } type ChatCardProps = { title: ...

Mocking store.dispatch in Jest with TypeScript did not result in any function calls being made

Testing Troubles I'm a beginner in the world of testing and I'm facing some challenges. Despite going through all the documentation on jest, I couldn't find information specific to TypeScript cases. Currently, I'm on a quest to figure ...

Issue with displaying entire object using Jest and console.dir

I'm having trouble displaying an error in my Jest test because it's not showing all the levels as expected. import util from 'util' describe('Module', () => { it('should display all levels WITHOUT util', () =& ...

Raycast failing to detect objects that have been displaced from their original starting position

I am facing a challenge with using a raycast to locate objects under the mouse cursor. The issue arises when the objects are not positioned at (0, 0, 0) as they cannot be detected by the raycast. Once I move the object to any other position, it no longer r ...

When using ngFor, a conversion from a string literal type to a regular string occurs, resulting in an error that states: "Element implicitly has an 'any' type because an expression of type 'string' cannot be utilized..."

When utilizing the iterator *ngFor, it converts a string union literal type ("apple" | "banana") to a string type. However, when attempting to use it as an index of an array expecting the correct string union literal type, an error occu ...

Finding the current URL in React Router can be achieved by using specific methods and properties provided by

Currently, I'm diving into the world of react-redux with react-router. On one of my pages, it's crucial to know which page the user clicked on to be directed to this new page. Is there a method within react-router that allows me to access inform ...