Error encountered following the upgrade of Angular and RxJS 5 to 6: Compilation failed

Since updating my libraries to the latest Angular 6 and RxJS 6, I've encountered an issue.

I have a RouteService class that functions as a service. It utilizes the HttpClient to fetch data from a remote API. However, after the update, I'm facing a strange error during project compilation.

This is my service class:

import {Injectable} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {Observable} from "rxjs/Rx";
import {catchError} from 'rxjs/operators';

export interface Route {
    name:string;
    route_id:number;
    created_at:Date;
}

@Injectable()
export class RouteService {
    constructor(private http:HttpClient) {}

    getRoutesList():Observable<Route[]> {
        return this.http.get<Route[]>(`http://localhost:8090/api/routes`)
        .pipe(catchError(ServiceUtil.handleError));
    }
}

Here’s the handleError method:

import {HttpErrorResponse} from '@angular/common/http';
import {ErrorObservable} from 'rxjs/observable/ErrorObservable';

export module ServiceUtil {
    export function handleError(error:HttpErrorResponse) {
        if (error.error instanceof ErrorEvent)
        console.error('An error occurred:', error.error.message);
        else 
        console.error('An error occurred:', JSON.stringify(error.error));    
        return new ErrorObservable(error.error);
    }
}

After running ng serve, I encounter the following error:

ERROR in src/app/service/route-service/route.service.ts(21,5): error TS2322: Type 'Observable<{} | Route[]>' is not assignable to type 'Observable<Route[]>'.
Type '{} | Route[]' is not assignable to type 'Route[]'.
    Type '{}' is not assignable to type 'Route[]'.
    Property 'includes' is missing in type '{}'.

Failed to compile.

What mistake am I making? Is there an issue in my code that is causing errors in the new versions but worked fine in the old ones?

Answer №1

According to the error message.

It is recommended to modify your method declaration as shown below:

getRoutesList():Observable<Route[] | {}>

Answer №2

Unexpectedly, the user of getRoutesList did not anticipate receiving a Route[].

getRoutesList(): Observable<any>

Alternatively, you can modify your error handling function handlerError to return:

return Observable.throw(error.error)

Answer №3

Following the suggestion of @Riscie, I have implemented an http interceptor and it is functioning as expected.

Below is a snippet of the code I used:

export class AngularInterceptor implements HttpInterceptor {
    intercept(req:HttpRequest<any>, next:HttpHandler):Observable<HttpEvent<any>> {
        return <any>next.handle(req)
        .pipe(timeout(5000), tap(event => {}, error => {
            if(error == null)
                throw {"message": "Unknown server error", "code": 987};
            else if(error.error != null) {
                if(error.error.code != null)
                    throw error.error;
                else if(error.status != null)
                    throw { "message": error.error.error, "code": error.status };          
            }
            else
                throw {"message": error+"", "code": 986}
        }));
    }
}

Can someone confirm this implementation is correct?

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

gulp-tsc cannot locate the src directory

I am currently working on developing a .NET Core application using Angular2, but I keep encountering the following error: /wwwroot/NodeLib/gulp-tsc/src/compiler.ts' not found. I'm having trouble pinpointing what I might be missing. tsconfig.js ...

Avoid using dot notation with objects and instead use `const` for declaring variables for more

interface obj { bar: string } function randomFunction() { let foo: obj = { bar: "" } foo.bar = "hip" } let snack: obj = { bar: "" } snack.bar = "hop" Upon transcompiling, a warning from tslint pops up: Identifier 'foo' is never reassi ...

Description: TypeScript type that derives from the third constructor parameter of a generic function

How can I determine the type of constructor props for a generic type? Take a look at this example. type PatchableProps<T> = T extends { [k: string | number]: any } ? { [Key in keyof T]: PatchableProps<T[Key]> } : T | Patch export class ...

Exploring ways to conduct a thorough scan of object values, inclusive of nested arrays

My goal is to extract all values from an object. This object also includes arrays, and those arrays contain objects that in turn can have arrays. function iterate(obj) { Object.keys(obj).forEach(key => { console.log(`key: ${key}, value: ${o ...

Understanding how to efficiently map through FontAwesome icons using React TypeScript and effectively showcase them on the frontend

I am in the process of developing a versatile component that allows me to input the href, target, and rel attributes, along with specifying the FontAwesome Icon I want to utilize. My goal is to be able to pass multiple icons into this list, which will then ...

Transferring data from a parent ng-template to a child ng-template

Is it possible to nest one ng-template inside another ng-template? If so, how can I pass data from the parent ng-template to its child ng-template? I have tried several methods, but none of them seem to work for me. <ng-template let-r="result" #rt&g ...

The PrimeNG dialog component stubbornly refuses to close even when clicking outside the modal

My modal dialog component from PrimeNG is structured like this <p-dialog header="{{title}}" [(visible)]="display" [modal]="true" [dismissableMask]="true" [closeOnEscape]="true" [responsive]="true" [closable]="false" > {{content}} </p-dialog&g ...

Populating a data grid with several objects within a JSON object

I am currently developing a project utilizing React with typescript and materialUi. My task is to retrieve data from a JSON fetch request and display it in a DataGrid. The structure of the JSON data is as follows: { id: "1234567890", number: ...

Visual Studio 2017, ASP.NET framework, Typescript programming language, and node package manager

My ASP.net application in Visual Studio used to only utilize JavaScript, but now I am looking to incorporate Typescript. While the installation and transpiling process went smoothly, I encountered an issue when attempting to import modules. I decided to u ...

Looking to customize the scrollbar style within an Angular Material table?

Is there a standard method for customizing the scrollbar design in an Angular Material table similar to the one displayed below? (I am unable to identify any applicable styling attributes through element inspection.) angular-table-issue ...

Cyrillic characters cannot be shown on vertices within Reagraph

I am currently developing a React application that involves displaying data on a graph. However, I have encountered an issue where Russian characters are not being displayed correctly on the nodes. I attempted to solve this by linking fonts using labelFont ...

Include form data into an array of objects within an Angular data source

I am struggling to add the edited form data from edit-customers-dialog.ts into an array of objects in my datasource. The form.data.value is returning correctly, but I'm facing issues with inserting it properly into the array. As a beginner in Angular ...

Tips for finding the displayRows paragraph within the MUI table pagination, nestled between the preceding and succeeding page buttons

Incorporating a Material-UI table pagination component into my React application, I am striving to position the text that indicates the current range of rows between the two action buttons (previous and next). <TablePagination ...

TypeScript overloading error: Anticipated 0 parameters, received 2 instead

I am facing an issue with a class containing an overloaded method that has two versions. One version does not take any arguments, while the second one can take two arguments. class DFD { ... getEndDatetime(): string; getEndDatetime(startTime?: ...

Discovering the data type in Typescript through the use of Generics

In my data structure, I am using generics to build it. However, when I try to populate data, I encounter the need to convert simple formats into the correct types. The issue arises as the class is configured with Generics, making it difficult for me to det ...

Struggling to bring in components in ReactJS

My journey with ReactJS has just begun, and I've encountered some issues with the code that I believe should work but doesn't. To start off, I set up a new ReactJS project using the npm command create-react-app. Following this, I installed Googl ...

`What exactly do auth.guard.ts and the AuthenticationService do in Angular 8?`

import { Injectable } from '@angular/core'; import { AuthenticationService } from './_services'; import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; @Injectable({ providedIn: & ...

Exploring the incorporation of interfaces into Vue.js/Typescript for variables. Tips?

I have an interface:   export interface TaskInterface{ name: string description1: string time: string } and a component import { TaskInterface } from '@/types/task.interface' data () { return { tasks: [ { name: 'Create ...

Is there a disparity in capabilities or drawbacks between ViewChild and Input/Output in Angular?

As I delve into Angular ViewChild and compare it to Input/Output parameters, I can't help but wonder if ViewChild has any drawbacks or limitations compared to Input/Output. It appears that ViewChild is the preferred method, as all parameters are now ...

Optimize your code in Angular 5 by consolidating or restructuring numerous Subscribe calls

Currently, I am utilizing Angular 5.2 for my web project. One of the pages includes multiple subscribe calls to various webAPI methods. While these calls are distinct and retrieve different datasets, I'm contemplating if there is a method to consolida ...