The "void" type cannot be assigned to the type "ObservableInput<{}>"

I recently encountered this issue after updating to TS 2.2.2, and I suspect that is the root cause... While the code still functions properly, I am now seeing this error. I attempted various solutions such as returning an empty observable, catching the re-thrown exception, and returning an object, but nothing seemed to resolve it. Why is this problem arising now? Shouldn't it recognize I am re-throwing the exception and not expect a return? Could I be misinterpreting the error message?

Here is the detailed description of the error:

https://i.sstatic.net/ePmFC.jpg

Below is the complete code snippet:

return request
    .map((res: Response) => res.json())
    .catch((error: any) => {
        // todo: log?

        if (error.status == 500) {
            this.alertService.showError(error.statusText);
        } else if (error.status == 588) {
            this.alertService.showAlert(error.statusText);
        }

        Observable.throw(error.statusText);
    });

I attempted to return the Observable, however, my wrapper method requires a return type T, which corresponds to the deserialized request's return value from map(...). If I do include the throw, I receive the following error message:

[ts] Type 'Observable' is not assignable to type 'T'

The technologies I am using are:

  • Angular4
  • Typescript 2.2.2

Answer №1

Make sure to send back the Observable

 return request
    .map((res: Response) => res.json())
    .catch((error: any) => {
        // remember to log?

        if (error.status == 500) {
            this.alertService.showError(error.statusText);
        } else if (error.status == 588) {
            this.alertService.showAlert(error.statusText);
        }

        return Observable.throw(error.statusText);
    });

Answer №2

At times, when catch is called without using an arrow function like in the example below

getUserList() {
    return this.http.get(this.constURL + '/api/url/here', this.headerOptions)
    .catch(this.handleError);
}

handleError(error: Response) {
    if (error.status == 500) {      
      this.router.navigate(['/login']);
    } else {
      return Observable.throw(error);
    }
}

an error occurs:

ERROR TypeError: Cannot read property 'navigate' of undefined because the this object is inaccessible in the handleError function..if you console this.router then you will get undefined.. so this object is not working and router methods are not accessible.

Thus, it is necessary to use an arrow function as shown below:

getUserList() {
    return this.http.get(this.constURL + '/api/url/here', this.headerOptions)
    .catch(error => { 
      return this.handleError(error);
    });
}

handleError(error: Response) {
    if (error.status == 500) {      
      this.router.navigate(['/login']);
    } else {
      return Observable.throw(error);
    }
}

Furthermore, if a return statement is not specified for the handleError function, another error will be thrown:

Argument of type '(error: any) => void' is not assignable to parameter of type.

Therefore, it is crucial to include a return statement for the handleError function.

For more detailed information, refer here. The author has explained the code comprehensively with solutions to possible errors, which worked effectively for me.

Answer №3

This solution addresses the usage of Angular 6 along with RXJS 6. When implementing your request function, it should resemble the following code snippet. Please note that catch has been updated to catchError, and Observable.throw is now throwError. Additionally, in RXJS 6, we utilize pipe to chain a sequence of functions together instead of dot chaining as seen previously.

//Within your service

getData(url: string): Observable<any> {
    let options = this.getHTTPOptions();
    return this.http.get<any>(url, options).pipe(
          catchError( (err: any, caught: Observable<any>) => { return throwError(this.generalErrorHandler(err, caught)) } ) );
}

An error handler can then be implemented. It is crucial to include the keyword return within both the catchError function above and the returned error in the handler function. With the arrow notation ( => ), you have access to the context of the calling function in the error handler, enabling operations such as

this.router.navigate(['someroute']);
(assuming the router is imported into your service).

//Within your service

  generalErrorHandler(error: any, caught: Observable<any>): Observable<any> {
    console.log('error caught: ', error);
    if( error.error.status == "INVALID_TOKEN" || error.error.status == "MAX_TOKEN_ISSUE_REACHED"){
      console.log('token has expired');
      this.logout();
      return error;
    }
    return error;
  }

Key imports required for this setup:

//Imports for the service

import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Http, Response } from '@angular/http';
import { catchError, map } from 'rxjs/operators';
import { Observable, throwError, of} from 'rxjs';

Lastly, to retrieve data by subscribing to the request:

//Within your component, remember to import your service

let response$ = this.someService.getData('url here');
response$.subscribe( 
    data => { console.log('perform operations on data here', data); },
    err => { console.log("unable to fetch data, consider displaying an error message to the user"); },
    () => { console.log('function executed upon completion'); }
);

Answer №4

 return Observable.throw(error);

The Observable. throw method is no longer recommended, instead use the throwError operator within the interceptor.

intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
   return next.handle(request).pipe(
    catchError(err => {
      if (err.status === 401) {
       // remove Bearer token and redirect to login page
        this.router.navigate(['/auth/login']);
      }
      return throwError( err );
    }));
}

Answer №5

Currently, using Angular 14, I was able to resolve the error by utilizing Error(err.error.message);.

For instance:

 handleAppError(err: any): Observable<any> 
{return new Error(err.error.message);}

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

Is there a way to transform time into a percentage with the help of the moment

I am looking to convert a specific time range into a percentage, but I'm unsure if moment.js is capable of handling this task. For example: let start = 08:00:00 // until let end = 09:00:00 In theory, this equates to 100%, however, my frontend data ...

Guide to successfully passing a function as a prop to a child component and invoking it within Vue

Is it really not recommended to pass a function as a prop to a child component in Vue? If I were to attempt this, how could I achieve it? Here is my current approach: Within my child component - <template> <b-card :style="{'overflow-y&apo ...

Underscore.js is failing to accurately filter out duplicates with _uniq

Currently, I am integrating underscorejs into my angular project to eliminate duplicate objects in an array. However, I have encountered an issue where only two string arrays are being kept at a time in biddingGroup. When someone else places a bid that is ...

What is the best approach to validating GraphQL query variables while utilizing Mock Service Worker?

When simulating a graphql query with a mock service worker (MSW), we need to verify that the variables passed to the query contain specific values. This involves more than just type validation using typescript typings. In our setup, we utilize jest along ...

Unable to access property 'create' which is undefined

On my Ionic3 page, I am trying to trigger a modal open from within a click event function. export class HomePage { .... .... .... loadPos() { var randomLocations = Microsoft.Maps.TestDataGenerator.getLocations(5, this.map.getBounds()); ...

Guide to customizing the appearance of a component's host element on-the-fly

For instance: https://stackblitz.com/edit/angular-mkcfsd In my project, I have an icon component called app-icon which dynamically takes a path and inserts it into an SVG viewbox. I extract the height and width of the path, then set the SVG to match those ...

Display dates in Angular with specific Timezone settings

I have a challenge where I am receiving dates in UTC format from my API and I need to display them using the user's local timezone, which is obtained from another API. While I was able to successfully handle time zones with a positive offset (e.g. +10 ...

The concept of a singleton design pattern is like a hidden treasure waiting to be

My approach to implementing the singleton pattern in a typescript ( version 2.1.6 ) class is as follows: export class NotificationsViewModel { private _myService: NotificationService; private _myArray: []; private static _instance: Notificatio ...

The updated values in an Angular application may not always be accurately represented by interpolated values

The values of the elements in the dropzone1 array only show the initial top and left values, not the latest ones. Within the draw() function, I add the top and left values to the topLeft array and then push it to the dropzone1 array inside the move() func ...

Issues have been reported regarding the paramMap item consistently returning null when working with Angular 8 routing

I am encountering an issue with Angular 8 where I am trying to fetch some parameters or data from the route but consistently getting empty values. The component resides within a lazy-loaded module called 'message'. app-routing.module.ts: ... { ...

Angular unable to send object to HTML page

Struggling with learning angular, encountering new challenges when working with objects in different components. In two separate instances, try to implement two different mechanisms (microservice or service component serving an object directly). This speci ...

What function does the ng-template serve when encapsulated within an ng-select component?

Upon observing various instances of ng-select, I've noticed that it often involves wrapping a ng-template, as exemplified below: <ng-select [items]="cities" [(ngModel)]="selectedCity" bindLabel="name" bindV ...

What is the best way to transition this endpoint from JavaScript to TypeScript?

I'm in the process of building a chat application with the t3 stack. I've successfully created a socket endpoint using JavaScript, but now I'm facing some challenges as I try to convert it to TypeScript. import { Server } from "Socket.I ...

The most efficient method for distributing code between TypeScript, nodejs, and JavaScript

I am looking to create a mono repository that includes the following elements: shared: a collection of TypeScript classes that are universally applicable WebClient: a react web application in JavaScript (which requires utilizing code from the shared folde ...

Using React and TypeScript to Consume Context with Higher Order Components (HOC)

Trying to incorporate the example Consuming Context with a HOC from React's documentation (React 16.3) into TypeScript (2.8) has been quite challenging for me. Here is the snippet of code provided in the React manual: const ThemeContext = React.creat ...

How can I set ion-option to be selected by tapping instead of having to click OK?

Currently, I am developing a mobile application and have encountered a scenario in which I utilized ion-option with ion-select, resulting in successful functionality. However, I am now aiming to remove the OK/CANCEL button so that users do not need to clic ...

Choose the Angular 2 option

I am having an issue with the select option in my code. The person's gender property is assigned 'M' for male, but I need to allow users to change it to 'F' for female. Here is the HTML code snippet: <span > <span &g ...

Guide on expanding the capabilities of IterableIterator in TypeScript

I am currently working on extending the functionality of Iterable by adding a where method, similar to C#'s Enumerable.where(). While it is straightforward to extend the Array prototype, I am encountering difficulties in figuring out how to extend an ...

Can someone explain why the Next 13 API route is showing up as empty?

I am currently working with Next 13 and I am attempting to create a simple API route. My goal is to have a: "hi" returned when I visit localhost:3000/api/auth. Despite not encountering a 404 error or any errors in the terminal or console, I can&a ...

Is it possible that React.createElement does not accept objects as valid react children?

I am working on a simple text component: import * as React from 'react' interface IProps { level: 't1' | 't2' | 't3', size: 's' | 'm' | 'l' | 'xl' | 'xxl', sub ...