I'm encountering an error after updating Angular/Typescript. The error message states that Type 'Observable<unknown>' cannot be assigned to type 'Observable<ProcResult[]>'

My Angular database service has been set up in this manner since Angular 6, and I am now encountering this error for the first time.

I have a standard HTTP POST method that returns a result. In case of an error, I want to handle it appropriately. The most common error being an expired token, which is handled specifically to log out the user.

POST

postUsp(username): Observable<ProcResult[]> {
  const url = hosturl +'u_sp';
  const httpOptions = {
    headers: new HttpHeaders({
      'Access-Control-Allow-Origin':  '*',
      'Content-Type': 'application/json',
      'Authorization': ls  || '{}'
    }),
    withCredentials: true,
    params: {
      'username': username,
    }
  };
  return this._http.post<ProcResult[]>(url, null, httpOptions)
  .pipe(
    map((res) => {
      return <ProcResult[]> res;
        }),
        catchError(this.handleError)
      )
}

handleError

private  handleError(error: Response | any) {
  if (error.status === 401) {
   console.log('Signing out.')
    try { 
      Auth.signOut().then(() => {
        window.location.reload()
      })
      return error
    } catch (error) { console.log('error signing out: ', error); }
  } else {
  return throwError(error);
  }
}

Full error output:

Error: src/app/db.service.ts:303:3 - error TS2322: Type 'Observable<unknown>' is not assignable to type 'Observable<ProcResult[]>'.
  Type 'unknown' is not assignable to type 'ProcResult[]'.

303   return this._http.post<ProcResult[]>(url, null, httpOptions)
      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
304   .pipe(
    ~~~~~~~~
...
309         catchError(this.handleError)
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
310       )

Answer №1

Make sure to include the throwError function within both the try and catch blocks.

private handleError(error: Response | any) {
    if (error.status === 401) {
      console.log('Signing out.');

      try {
        Auth.signOut().then(() => {
          window.location.reload()
        })

        return throwError(error);
      } catch (error) {
        console.log('An error occurred while signing out: ', error);

        return throwError(error);
      }
    } else {
      return throwError(error);
    }
}

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

Postponing a function invocation in an Angular/TypeScript application

I am facing a challenge in my Angular project. I have a form on one of my pages that allows users to submit data which is then sent to the database. However, after submitting the data, I need to delete the user's information from one table and insert ...

Angular template src variable issue with no solution in sight

The videoSrc variable is not evaluating correctly images/{{videoSrc}}.mp4 When I write just videoSrc, it works fine. But when I concatenate it with other strings, it doesn't work. Check out this jsfiddle ...

Having trouble retrieving a value from a reference object in React Typescript?

Struggling with a login form issue in my React TypeScript project. Below is the code for the react login form: login-form.tsx import * as React from 'react'; import { Button, FormGroup, Input, Label } from 'reactstrap' ...

Comparing plain objects and class instances for modeling data objects

What is the recommended approach for creating model objects in Angular using TypeScript? Is it advisable to use type annotation with object notation (where objects are plain instances of Object)? For example, let m: MyModel = { name: 'foo' } ...

Assign the JSON response to a variable and then display it

I am currently working on a form that sends a combination of Zip code and house number to an external page. The external page then responds with a JSON containing address information. Although the process is functional, I am struggling to figure out how t ...

Chrome is displaying an error message: "The origin file:// is not permitted by Access-Control-Allow-Origin."

Currently, I am in the process of developing a Chrome extension that requires access to a site called minus.com, which implements oAuth 2.0 for authentication. To facilitate this, I have created a javascript file named 'test.js' and integrated it ...

What is the best way to handle multiple JSON data using jQuery?

Understanding how to utilize jquery for parsing simple json is a valuable skill. json { "Symbol": "AAL.L", "Name": "ANGLO AMERICAN", "Last": "3061.50", "Date": "7/26/2011", "Time": "11:35am", "Change": "+3 ...

AngularJS - Custom directive to extract a property value from an object

Currently, I am using the following for loop to retrieve the parent category: angular.forEach(queryTicketCategories, function(category) { if(category.id === $scope.ticketCategory.parentId) { $scope.parent = category; } }); I am looking fo ...

Tips for concealing the body description on the homepage of a blogger website

I want to conceal this description This is my blog and I am facing an issue where I need to hide the description on the home page. I have tried using color:white which worked initially, but when I moved the description to the top or left, the black backgro ...

Issue with NG Style not binding to page as expected

I am currently working on creating a web page with two sections that can be horizontally slid back and forth to occupy different widths on the page. My idea was to monitor the width percentage of the draggable bar that separates the two panes/sections, and ...

Proper method for verifying line-clamp in a Vue component

I came across a question that aligns perfectly with my current task - determining if text is truncated or not. The query can be found here: How can I check whether line-clamp is enabled?. It seems like my approach may not be accurate, so any guidance on ho ...

Is having only one FCM token sufficient for storing data from multiple devices?

I'm currently working on an Angular website and looking to send push notifications to users subscribed on both desktop and mobile. I am utilizing Firebase Cloud Messaging for this purpose and wondering if storing a single FCM token will suffice for se ...

Laravel vue infinite scroll failing to load additional content

I've been trying to implement the infinite scroll feature from Element UI in my app, but for some reason, it's just not working. Here's a snippet of my code: Code script // Your JavaScript code goes here ...

Angular 2 and beyond: Accessing a child element using @ViewChild()

Is it possible to access the child elements (specifically <img>) of @ViewChild() in Angular 2+ without explicitly declaring them? Within template.html <div #parent> <!-- Other elements besides <img> can also be present --> < ...

How to use Angular 2 to communicate with JavaScript API whenever the router switches to

I am currently working on an Angular2 component that has a template which relies on JavaScript calls to load various components such as Facebook, Google Maps, and custom scripts. The necessary scripts are already loaded in the index.html file, so all I ne ...

JavaScript visibility disappearing intermittently

I have created a custom image viewer box that overlays a thumbnail gallery page. The image viewer should appear when a user clicks on a thumbnail. However, currently, the viewer only pops up briefly and then disappears again. I am looking for a way to mak ...

What sets typescript apart when using a getter versus a regular function?

Imagine having a class with two methods declared for exclusive use within that class. // 1. private get something() { return 0; } // 2. private getSomething() { return 0; } While I am familiar with getters and setters, I'm intrigued to know if ther ...

Transferring JavaScript files via Node server using NowJS

As someone new to Node, I need some help with a server-client web application I'm creating for a board game using Raphael for graphics. The issue I'm facing is that while the server successfully sends the HTML file in response to requests, the b ...

Tips for resolving the UNABLE_TO_GET_ISSUER_CERT_LOCALLY issue while attempting to install Sentry using npm or curl

https://i.stack.imgur.com/G8hfZ.png curl -sL -k https://sentry.io/get-cli/ | bash Even though I've specified not to verify the certificate with -k, I'm still facing issues trying to install it. The script is supposed to automatically install sen ...

Materialize CSS is throwing an error: 'velocity is not a function'

Encountering an issue with Materialize CSS. A JavaScript error appears 'I('.velocity is not a function', for certain actions. For instance, clicking the collapse icon on the sidenav results in e.velocity is not a function error. Similarly, u ...