Angular's promise is incompatible with the type ts2322 and cannot be assigned

Struggling to implement a login feature in Angular, encountering an error related to promises: "Type 'Promise<ApiResponse<UserLogged> | undefined>' is not assignable to type 'Promise<ApiResponse<UserLogged>>'. ts2322

     login(user?:string, password?:string):Promise<ApiResponse<User>> {
      return new Promise((resolve) =>  {
        let promise:Promise<ApiResponse<UserLogged>>;
        if (user && password)                           //logging in
          promise=this.http.post<ApiResponse<UserLogged>>(this.baseUrl + "login", {user: user, password: password}).toPromise();
        else                                            //checking for active session on the server
          promise=this.http.get<ApiResponse<UserLogged>>(this.baseUrl + "login").toPromise();
        //process response
  
      });
      
    }

apiresponse.ts

export interface ApiResponse<T> extends BaseDTO{
  status: number;
  message?: string;
  data?: T
}

baseDTO

export interface BaseDTO { 
}

Seeking clarification on my mistake.

Apologies for my poor English.

Thank you.

User

export interface User extends BaseIdDTO{
  user:string;
  password?:string;
  mail:string;
  name?:string

Resolved the issue by changing the tsconfig.json from "strict:true" to "strict:false". Error disappeared.

Answer №1

Thank you for your advice! As a novice in this field, I am eager to learn more about implementing it using observables.

Answer №2

Is it important to start with clean code?

login(user?: string, password?: string) {
  if (user && password) return this.http.post(this.baseUrl + 'login', { user, password }).toPromise();
  else return this.http.post(this.baseUrl + 'login').toPromise();
}

Furthermore, embracing observables is highly recommended over using promises as they offer more benefits.

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

Diving into Angular 2 RC6: Understanding the Differences Between Modules and Components

I'm feeling a bit overwhelmed with RC6 of angular2. I'm struggling to figure out how to adjust my code with modules and components and I'm confused about the distinctions between the two. Can you assist me in incorporating directives, provid ...

After 6 minutes of inactivity, queues are automatically deleted when the Android tablet enters standby mode

Once the client (also known as the browser) goes into sleep mode, it stops receiving new updates from the subscribed queue after about 6 minutes. Upon checking RabbitMQ Management, I noticed that the related queues (like stomp-subscription-MBSsZ9XB0XCScXbS ...

How is it possible for this for loop to function properly without the need to pass the incrementing variable

I managed to compile my code and it's working fine, but there's something interesting - the variable that should reference the incrementing value is not included as an argument in the for loop. var _loop2 = function _loop2() { var p = docume ...

Leveraging Google Analytics with Angular 4 and beyond

Having trouble integrating Google Analytics with Angular 4? Can't seem to find the @type for ga.js in ts? Here's a quick fix that I implemented in every component: declare let ga: any; How did I solve it, you ask? I created a function to dyna ...

Managing the browser's "back" button functionality in React

I am currently using "react-dom-router v6.3.0" (strictly!) and I am struggling to figure out how to manage the browser's "back" button functionality. Specifically, I want to be able to detect when the user clicks the back button so that I can display ...

Having trouble uploading a file with Angular and Spring

The issue of uploading files to BE is causing me some trouble. I have been struggling to get it right, even with the code below: Angular service public saveFile(file: File): Observable<any> { const formData = new FormData(); formDat ...

Mastering the art of throwing and managing custom errors from the server to the client side within Next.js

I'm in the process of developing a Next.js application and I am faced with the challenge of transmitting customized error messages from the server to the client side while utilizing Next JS new server-side actions. Although my server-side code is func ...

Converting API response into a class instance using `class-transformer` in TypeScript: A step-by-step guide

When working with TypeScript, I have a regular method called Request(method: HttpMethod, url: string, ...) that is used for calling APIs. Now, my goal is to convert the response from this API request into an instance of a class using class-transformer (or ...

Error message encountered during angular project build using ng build: angular.json file missing

I had successfully created a project on my laptop a month ago and didn't encounter any errors. However, when I cloned the repository to a new computer today, I encountered some issues. After running 'npm i' to install packages, I attempted t ...

Show the alias of a type in Vscode Typescript instead of its definition

Here is some code that I am working with: type Opaque<T,U> = T & {_:U}; type EKey = Opaque<number,'EKey'>; type AKey = Opaque<EKey,'AKey'>; type PKey = Opaque<AKey,'PKey'>; let a = <PKey>1; ...

Incorporate a 'Select All' functionality into ion-select by adding a dedicated button

Looking for a way to set custom buttons on ion-select through interfaceOptions in ionic 4? HTML <ion-item> <ion-label>Lines</ion-label> <ion-select multiple="true" [(ngModel)]="SelectedLines" [interfaceOptions]="customAlertOption ...

How to properly handle Angular routing errors and best practices?

Currently, I have been delving into learning Angular to integrate with my Ruby on Rails application. However, I have encountered some challenges specifically related to routing. Here is a snippet from my app.routing file: import { NgModule } from '@ ...

Validation in custom components within an Angular reactive form is failing to function correctly

Currently, I am in the process of developing a new component within Angular reactive forms. To view my sample project: https://stackblitz.com/edit/angular-pyi9jn The angular form I created follows this structure: form - simple counter The form output i ...

"Guidance on setting up my input text box in Angular to allow for selection of required fields

I'm currently in the process of developing a form where all fields are required. My goal is to have the Next button move on to the subsequent form only if all required fields have been filled out. However, I seem to be encountering an issue where desp ...

Managing Geolocation in Ionic2 presenting challenges

Attempting to utilize Geolocation in ionic2 for device location access. Referred to the official documentation on https://ionicframework.com/docs/native/geolocation/. Successfully installed the necessary packages: $ ionic plugin add cordova-plugin-geoloca ...

How can React TypeScript bind an array to routes effectively?

In my project, I am using the standard VisualStudio 2017 ASP.NET Core 2.0 React Template. There is a class Home included in the template: import { RouteComponentProps } from 'react-router'; export class Home extends React.Component<Rout ...

Angular's asynchronous HTTP request allows for non-blocking operations when

I'm currently working with Angular 6, and I've encountered an issue while updating my resource instance in the following way: this.user = api.getUser(); public getUser(): User { const myHeader = new HttpHeaders({ 'Authorization' ...

What is the best way to send headers to the ngx-logger's post method for a server URL?

We are currently considering the use of ngx-logger in Angular 4 for server logging. However, we have encountered an issue with passing headers along with the serverLoggingUrl. BrowserModule, HttpModule, LoggerModule.forRoot( { serverLoggingUrl: &ap ...

Step-by-step guide to developing an Angular 2+ component and publishing it on npm

I need assistance with creating an AngularX (2+) component and getting it published on npm. My objective is to publish a modal component I developed in my current Angular App, though currently, I am focusing on creating a <hello-world> component. It ...

The post method is functioning properly in browsers such as Firefox, Internet Explorer, and Chrome; however, it is not working in the Edge browser

I am encountering an issue with a post method in the Edge browser. Even though I am able to receive responses for the same request in other browsers like Internet Explorer, Chrome, and Firefox, Edge seems to be not responding at all. Despite conducting a s ...