Dealing with Errors in Angular 5 using Observables: Why Observable.throw isn't working

Can someone assist with resolving this issue?

Error message: core.js:1542 ERROR TypeError: rxjs__WEBPACK_IMPORTED_MODULE_3__.Observable.throw is not a function

Software versions: Angular CLI: 6.0.8 / rxjs 6.2.1

import { Injectable } from '@angular/core';
import { User } from './../classes/user';
import { AppSettings } from './appSettings';
import { HttpClient,HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

@Injectable({
      providedIn: 'root'
})

export class LoginService {

      constructor(private http: HttpClient){ }

      login(user:User): Observable<User> {                               
            return this.http.post<User>(AppSettings.BASE_URL + "/login",user)
            .pipe(catchError(this.handleServerError));   
      }

      handleServerError(error: any  | any) {
            console.log(error.error || error.json() || error);
            return Observable.throw(error.error || error.json() || error || 'Server error');  <<< ERROR
      }

}

Answer №1

This is my solution:

app.module.ts

 import {HttpClientModule} from '@angular/common/http';
 .
 .
 . 
 imports: [
    BrowserModule,
    HttpClientModule
  ]

service/login.ts

import { Injectable } from '@angular/core';
import { User } from './../classes/user';
import { AppSettings } from './appSettings';
import { HttpClient,HttpHeaders, HttpParams } from '@angular/common/http';
import {  throwError } from 'rxjs';
import { Observable, Subject, ReplaySubject, from, of, range } from 'rxjs';
import { map, filter, switchMap } from 'rxjs/operators';
import { catchError, retry } from 'rxjs/operators';

const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json',
        'Authorization': 'my-auth-token'
      })}


@Injectable({
      providedIn: 'root'
})

export class LoginService {

      constructor(private http: HttpClient){

      }

      login(user:User): Observable<User> {                               
            return this.http.post<User>(AppSettings.BASE_URL + "/login",user)
            .pipe(catchError(this.handleServerError));   
      }

      handleServerError(error: any | any ) {
            console.log(error.error || error.json() || error);
            return throwError(error.error || error.json() || error || 'Server error');
      }

}

login.component.ts

 import { LoginService } from '../../services/login';

this.loginService.login(new User("admin","admin")).subscribe(                  
                  user => {
                        //to do ; 
                  },
                  error => {                                                  
                         throw 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

Tips for correctly passing the type of combineReducers: I encountered an error saying "Property '...' does not exist on type 'Reducer<CombinedState{}>"

I am currently integrating TypeScript into my react/redux project. Unfortunately, I am encountering an error that is preventing my app from loading. The issue is shown in the screenshot below: https://i.sstatic.net/HkPwo.png Within my index.tsx file, I a ...

Preventing Firebase duplicates leads to the error of not being able to read the property 'apps'

Struggling to incorporate Firebase into a TypeScript/NextJS project, I have encountered difficulties. Despite successfully importing and initializing the app: import * as firebase from "firebase/app"; import { collection, getDocs } from "fir ...

ESLint encountered an issue: Reserved keyword 'interface' triggered a parsing error

Whenever I utilize the most recent version of eslint to initiate a project, a specific error pops up: import { ref } from 'vue' defineProps<{msg: string}>() const count = ref(0) Error message: Unexpected token )eslint Adjusting the code ...

AOT compile error due to Angular interpolation syntax

I am facing an issue while compiling my application. The AOT compiler is showing an error related to Angular interpolation in an Angular 2 form: Property 'address' does not exist on type 'FirebaseObjectObservable'. Here's a sn ...

The Angular Button fails to display when all input conditions are met

I'm currently working on validating a form using this link. The requirement is simple - when an input field is invalid, the `save` button should be disabled. Conversely, when all input fields are valid, the `SAVE` button should be enabled/shown. The & ...

The refresh function in the table is not working as expected when implemented in a functional component. The table being used is Material

I am currently utilizing MaterialTable from https://material-table.com/#/docs/features/editable to manage data and perform CRUD operations within my application. I am seeking a way to automatically refresh the table data after any CRUD operation (add, upda ...

What sets apart gzip from x-gzip content? And how can I decompress x-gzip specifically? zlib appears to be struggling

One of my npm libraries, named "by-request", has the ability to auto-decompress web content. A snippet of code from this library that handles auto-decompression is shown below: if (!options.dontDecompress || !binary) { if (contentEncoding ...

Hamburger Menu in Bootstrap not functioning as expected

Despite following each step meticulously for implementing the Hamburger menu in the navbar, I encountered an issue. The navbar collapses when resizing the window but fails to open upon clicking it. Below is a sample code snippet for reference. It utilizes ...

How Angular services transmit information to components

I have implemented a search field within my top-bar component and I am facing an issue in passing the input value of that search field to another component. Design Search service Top bar component Result component Operation Top bar component receives th ...

Angular 2, Release Candidate 5 - Dropdown form includes mysterious "phantom" choice

While working with Angular 2, RC 5, I have encountered a strange issue while building a form to create a new model object. The problem arises when there is an extra blank <option> appearing in the dropdown list after transpiling the code, even though ...

A guide to effectively unit testing StripeJs within the Karma testing framework for Angular 8

I'm currently facing a challenge in unit testing a payment component that relies on StripeJS. In my 'ng-app.js' file, I import it as follows: stripe: /*@ngInject*/ function ($ocLazyLoad) { return $ocLazyLoad.load({ ...

Next.js experiencing hydration error due to dynamic component

Having an issue with my RandomShape component, where it should display a random SVG shape each time the page is reloaded. However, I am encountering a hydration error on the client side. import React from "react"; import shapes, { getRandomShape ...

Steps to eliminate the Bearer authorization header in an Angular 4 POST request to an API

Is it possible to exclude the Authorization Bearer in a POST request? The following code was not successful in removing the authorization bearer that is being added by the HTTP interceptors. Error: 403 - Unauthorized Request. The Authorization header is ...

Styling the checked state of a switch in NativeScript/Angular with ngModel/FormBuilder

Let's explore the styling of a switch element within Angular: <Switch class="switch" formControlName="answer"></Switch> One approach involves targeting the switch with checked attribute, setting its background-color and text color accord ...

Exploring the implementation of query parameters in Nest.js

I am currently a freshman in the world of Nest.js. Below is an excerpt from my code: @Get('findByFilter/:params') async findByFilter(@Query() query): Promise<Article[]> { } I have utilized Postman to test this specific router. ht ...

What is preventing the exclusion of the null type in this specific situation within Typescript?

type NonNullableCopy<O> = { [p in keyof O] -?: O[p] extends null | undefined ? never : O[p]; }; type Adsa = {a?: number | null} type Basda = NonNullableCopy<Adsa> let asd : Basda = { a: null // Still valid. No errors } Although it see ...

Bespoke directive - Angular 2/4/5

Currently, I am using Angular 5 CLI but for some reason my custom directive is not working as expected. There are no errors showing up in the console either. I am trying to apply some styles to make the image fill the full width. Below are two different i ...

Removing a directory from GitHub with the help of octokit/rest

I am attempting to utilize octokit/rest in order to programmatically remove a directory. Below is the code I am using: import {Octokit as Github} from '@octokit/rest'; const githubToken = "read from vault"; // Functions for retrieving current c ...

Choose the AuthGuard category in real-time

My application intends to employ two distinct authentication strategies - one for users accessing via a browser and another for the public API. A specific header will be set for browser users, allowing my app to determine the appropriate auth strategy base ...

Accessing results from geocoder.geocode is restricted to local variables only

I need to extract longitude and latitude coordinates from google.maps.GeocodeResults in order to store them in an external Array<any>. Currently, I am able to display results[0], but encounter an OVER_QUERY_LIMIT error when attempting to add it to t ...