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

Unable to Anticipate User Input in Angular Using Scanner or Keyboard

Currently grappling with Angular 6 and facing an issue. I have a text box and a submit button, with a requirement for functionality to allow input through either manual keyboard typing or a Barcode scanner. The desired behavior is for the submit button to ...

Fade In Effect in Angular 2 Using SwitchCase

Hi everyone, I'm facing an issue with making my switch cases fade in after one is called. Here's what I have so far. When the correct switch case is entered in the input field, I want the current one to fade out and the new one to fade in. How ...

Adjust the control's value as you monitor any modifications

As I monitor the changes within a reactive form by subscribing to the value changes, I have encountered an issue where certain values unset in the form prevent the Angular Material Slide Toggle from toggling to false. This is crucial as it affects the "Act ...

Event callback type narrowing based on the specific event key

While exploring different approaches to create a type-safe event emitter, I came across a pattern where you start by defining your event names and their corresponding types in an interface, as shown below: interface UserEvents { nameChanged: string; ...

Ways to define an interface that can accommodate various interfaces with a specific structure

I am in need of a function that can accept a parameter with interfaces having a specific structure. The parameter should be either a string hash or a string hash along with an attribute string hash, as shown below: { anotherHash: { a: 'a', ...

Encountered an error while trying to update information in Angular

I have been working on a project involving a .NET Core Web API and Angular 11 (Full-Stack) project. I have successfully managed to add data to the database in my back-end, but I am encountering an issue when trying to update the data. Below is a snippet o ...

What is the correct way to initialize and assign an observable in Angular using AngularFire2?

Currently utilizing Angular 6 along with Rxjs 6. A certain piece of code continuously throws undefined at the ListFormsComponent, until it finally displays the data once the Observable is assigned by calling the getForms() method. The execution of getForm ...

The issue with importing fonts in CSS causing an error is encountered when utilizing an exported Angular library

I have a components library for Angular that relies on line-awesome icons. To include the necessary fonts and styles, I am using a CDN in the main SCSS file as shown below: @import url('https://fonts.googleapis.com/css2?family=Nunito:wght@200;300;400; ...

updating rows in a table

Currently, I have a grid array filled with default data retrieved from the database. This data is then displayed on the front end in a table/grid format allowing users to add and delete rows. When a row is added, I only want to insert an empty object. The ...

Display a loading screen while transitioning between routes in Angular 2

Is there a way to implement a loading screen for route changes in Angular 2? ...

Having trouble accessing the application on localhost

I'm diving into the world of Docker! I'm looking to build a personalized docker image for an Angular application using a Dockerfile. I've successfully created the image and got the container up and running, but unfortunately, I'm unable ...

Error in Subscribing to Angular 8 Async Pipe

Check out this Full StackBlitz example: https://stackblitz.com/edit/angular8-async-pipe The app component template contains three identical components: <app-loader></app-loader> <app-progress></app-progress> <app-spinner>< ...

At first, the Angular disabled property does not seem to be functioning as

Trying to toggle a button's disabled state based on whether an array is empty or not in an Angular application. The button implementation looks like this: <button (click)="doStuff()" [disabled]="myObject.myArray.length === 0"> ...

Is there a comparable alternative to <ion-forward>?

I have a brand new module where users input information across 3 separate pages. Page 1: basic details with a continue button Page 2: additional info with another continue button and Page 3: the final submission Currently, when navigating back from Page ...

Create an instance of a class from a group of subclasses, all the while retaining the ability to access static members in Types

I seem to have encountered a dilemma where I am looking to have both the static and abstract keywords used for a member of an abstract class in TypeScript, but it appears that this combination is not supported. The nearest workaround I could come up with ...

Attempting to access a specific JSON key using Observables

Apologies for the question, but I'm relatively new to Typescript and Ionic, and I find myself a bit lost on how to proceed. I have a JSON file containing 150 entries that follow a quite simple interface declaration: export interface ReverseWords { id ...

A guide to teaching TypeScript to automatically determine the type of dynamic new() calls

One of the challenges I'm facing involves dynamically creating subclasses and ensuring that the factory function is aware of the subclass's return type. While I can currently achieve this using a cast, I am exploring options to infer the return ...

Error: The file or directory specified at ' ode_modules@fullcalendarcommon' does not exist

While attempting to build or serve my Angular project, I encountered the following error: 'An unhandled exception occurred: ENOENT: no such file or directory, lstat '\node_modules@fullcalendar\common' See "\AppData\ ...

How can I make sure that another function will only be executed after the completion of a function in

I'm currently working on an app with Angular CLI, and I am trying to retrieve a list after an insertion. Despite trying various methods such as observer, promise, async, setTimeout, etc., I haven't been able to find the right solution yet. I feel ...

Troubleshooting Angular 2 routing: when routerLink is empty, it fails to function

As I configure my routing, I encountered a problem. At the moment, these are my 2 routes: const appRoutes: Routes = [ { path: '', component: HomeComponent }, { path: 'products', component: ProductComponent} ]; Is it not allow ...