Upgrading from Angular 4 to Angular 5 may result in the following error message: "Error TS2322: The type 'Promise<void | LineSideInspection>' is not compatible with the type 'Promise<LineSideInspection>'"

I recently updated my Angular project from version 4 to 5.0 and started encountering an error. The code for the entire project (in Angular 4) can be found on github at https://github.com/SudhirSahoo/IQS

ERROR in src/app/lineside-inspection/lineside-inspection.service.ts(44,9): error TS2322: Type 'Promise<void | LineSideInspection>' is not assigna
ble to type 'Promise<LineSideInspection>'.
  Type 'void | LineSideInspection' is not assignable to type 'LineSideInspection'.
    Type 'void' is not assignable to type 'LineSideInspection'.
src/app/lineside-inspection/lineside-inspection.service.ts(50,64): error TS2339: Property 'rankAcount' does not exist on type 'Response'.
src/app/lineside-inspection/lineside-inspection.service.ts(51,64): error TS2339: Property 'rankBcount' does not exist on type 'Response'.
src/app/lineside-inspection/lineside-inspec...

<p>Code:</p>

<pre><code>update(inspection: LineSideInspection): Promise<LineSideInspection> {
        const url = '/api/inspection/updatecount/';
        let rankName = inspection.rankName;
        return this.http
            .post(url, JSON.stringify(inspection), {headers: this.headers})
            .toPromise()
            .then(response => {
                let data = response.json();
                if (rankName='A') inspection.rankAcount = data.rankAcount;
                if (rankName='B') inspection.rankBcount = data.rankBcount;
                if (rankName='C') inspection.rankCcount = data.rankCcount;
                return response.json() as LineSideInspection;
            })
            .catch(error => {
                alert("error");
            });
    }

If I change the return type to any, then I am not getting that error while ng build.

update(inspection: LineSideInspection): any {
        const url = '/api/inspection/updatecount/';
        let rankName = inspection.rankName;
        return this.http

Do I really have to change the return type everywhere?

Answer №1

One reason for this issue is that your catch block returns void, giving you two possible solutions.

The first option is to eliminate the catch block from your update method and manage errors in a different part of your code.

update(inspection: LineSideInspection): Promise < LineSideInspection > {
  const url = '/api/inspection/updatecount/';
  let rankName = inspection.rankName;
  return this.http
    .post(url, JSON.stringify(inspection), {
      headers: this.headers
    })
    .toPromise()
    .then(response => {
      let data = response.json();
      if (rankName = 'A') inspection.rankAcount = data.rankAcount;
      if (rankName = 'B') inspection.rankBcount = data.rankBcount;
      if (rankName = 'C') inspection.rankCcount = data.rankCcount;
      return response.json() as LineSideInspection;
    })
    // .catch(error => {
    //  alert("error");
    // });
}

Another approach is to return an object matching LineSideInspection using the catch operator.

import { of
} from 'rxjs/observable/of';

update(inspection: LineSideInspection): Promise < LineSideInspection > {
  const url = '/api/inspection/updatecount/';
  let rankName = inspection.rankName;
  return this.http
    .post(url, JSON.stringify(inspection), {
      headers: this.headers
    })
    .toPromise()
    .then(response => {
      let data = response.json();
      if (rankName = 'A') inspection.rankAcount = data.rankAcount;
      if (rankName = 'B') inspection.rankBcount = data.rankBcount;
      if (rankName = 'C') inspection.rankCcount = data.rankCcount;
      return response.json() as LineSideInspection;
    })
    .catch(error => of({} as LineSideInspection))
}

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

Solving the problem of cookieParser implementation in NestJS

Greetings! I have a question for you. Currently, I am working on developing a backend using NestJS, a Node.js framework. Everything is functioning smoothly except for some issues when it comes to hosting. I have created a new NestJS project and made some ...

Is there a way to utilize an AXIOS GET response from one component in a different component?

I'm having trouble getting my answer from App.tsx, as I keep getting an error saying data.map is not a function. Can anyone offer some assistance? App.tsx import React, {useState} from 'react'; import axios from "axios"; import {g ...

Ng-Select does not support disabling elements in conjunction with Bootstrap 4

After implementing ng-select (https://github.com/ng-select/ng-select) in my Angular 6 project and updating to Bootstrap 4, I encountered a problem with my custom logic for disabling elements. <ng-select style="width: 500px;" [multiple]="true" ...

Displaying a portion of the chart's key in a Highcharts BarChart

I need assistance displaying a partial legend (such as min, medium, max) for the X and Y axes, along with a horizontal dashed line at the medium point of the Y axis in a HighCharts BarChart. The graph is compact on the screen, serving as a summary of multi ...

Assistance with Angular: Utilizing a Spring Boot backend

Currently, I am in the process of developing a proof of concept for Angular with a Springboot backend. The code snippet below is related to interactions with the EmployeeService. However, this particular section seems to be malfunctioning as the control is ...

Can you provide guidance on how to divide a series of dates and times into an array based

Given a startDate and an endDate, I am looking to split them into an array of time slots indicated by the duration provided. This is not a numerical pagination, but rather dividing a time range. In my TypeScript code: startDate: Date; endDate: Date; time ...

Trouble with implementing a custom attribute directive in Angular 4 and Ionic 3

Hello, I am currently working on implementing a search input field focus using a directive that has been exported from directives.module.ts. The directives.module is properly imported into the app.module.ts file. However, when attempting to use the direc ...

Tips for sorting through and minimizing data based on the most recent date

info = { start: 1, data: [ { name: 'Maria', date: '2020-02-15 }, { name: 'Paula', date: '2020-06-10 }, { name: 'Eva', date: '2020-12-05 }, { name: 'Sophia', date ...

Uploading Files with Django Rest Framework and Angular 2

I am working with Django Rest Framework and Angular 2 to implement a file upload feature. Below is my code structure for handling files. Can anyone point out where I might be going wrong? Any help is greatly appreciated. Thank you! Django file: view cla ...

Is it advisable to utilize the vendorChunk feature in Angular for production purposes?

Incorporating Angular6 and pondering about whether setting "vendorChunk" to true or false is more advantageous in a production environment. While I understand its functionality, I am uncertain about the optimal value for usage in production scenarios. ...

Angular2: Adding a new array to all objects within an existing array

I am working with a REST API that delivers data in JSON format. I have stored this data in an array of objects, but now I want to add a new empty array to each object which is proving to be challenging. Below is a snippet of how my REST API data is structu ...

collaborating on data within closely related components in a table display

I am trying to figure out the best way to pass data among sibling components. For example, let's say I have a data entry grid structured like this: <tr *ngFor="let item of frm.controls.items.controls; let i=index" [formGroupName]="i"> <td ...

Retrieve a zip file using Angular RX and extract its contents

I am receiving a zip file from the backend and I need to extract its contents (which consist of a collection of JSON files for large offline data). API call: getOfflineTimetables() { let req = new Request(myOptions); return this.http.request(req ...

What could be causing IE11 to cut off my JavaScript file prematurely?

Edit: I believe I have resolved the issue, and it seems to be more related to Angular than I initially thought. The problem was caused by a fat arrow in the script, which was not easily visible due to code minification. This script is a global script that ...

Errors in Visual Studio regarding typescript are often not found by tsc and eslint, causing frustration for developers

Today, after restarting my computer and launching visual studio code, I encountered an unfamiliar error that I've never seen before: https://i.sstatic.net/z1vw5.png I haven't made any changes to my project's code (confirmed by running git ...

Different ways to update the AutoComplete Style attribute

MuiInput-formControl { margin-top: 16px; Is there a way to reset the marginTop property to zero? I attempted the following method, but it was not successful. MuiFormControlLabel: { marginTop: 0, }, <Autocomplete disabl ...

Angular allows you to easily upload multiple files at once

I am currently facing an issue while attempting to upload multiple files. There seems to be an error somewhere in my code that I have yet to identify. The problem is that nothing is being displayed in the console, but the 'uploadData' appears to ...

Anticipate an asynchronous function causing an error in a Jest test scenario

If I were to play around and execute the code snippet below: await expect(async () => { const asyncFunc = async () => { return Promise.reject(new Error('Foo')) }; await asyncFunc(); }).toThrow(); I assumed ...

The command '. .' is not valid for running npm install with firebaseUI

I am facing an issue while trying to install npm packages on my firebaseUI demo application. After cloning the master branch from Github, I attempted to run "npm install" but encountered an error that is new to me with Node Package Manager. The error messa ...

Tips on enabling typing support in VS Code and the tsc command for modules that do not use @types?

Currently, I am utilizing the "Rhea" module (https://www.npmjs.com/package/rhea) in my project. This module has its own typings for typescript located in the /typings folder within the module directory (/node_modules/rhea/typings). This differs from the us ...